Practice
count after the loop finishes when the input is [1, 5, 4]?
def wiggleMaxLength(nums):
if not nums:
return 0
count = 1
last_diff = 0
for i in range(1, len(nums)):
diff = nums[i] - nums[i - 1]
if (diff > 0 and last_diff <= 0) or (diff < 0 and last_diff >= 0):
count += 1
last_diff = diff
return count
Solution
Step 1: Trace loop iterations
Input: [1, 5, 4] - i=1: diff=5-1=4 >0 and last_diff=0 ≤0 -> count=2, last_diff=4 - i=2: diff=4-5=-1 <0 and last_diff=4 ≥0 -> count=3, last_diff=-1Step 2: Final count value
After loop, count=3, which is the length of the longest wiggle subsequence.Final Answer:
Option B -> Option BQuick Check:
Count increments twice for valid wiggles [OK]
- Off-by-one counting
- Ignoring initial count=1
- Not updating last_diff correctly
Solution
Step 1: Identify sorting costs
Sorting greed array of size n costs O(n log n), sorting cookies array of size m costs O(m log m).Step 2: Analyze assignment loop
Two pointers scan both arrays once, costing O(n + m).Final Answer:
Option C -> Option CQuick Check:
Sorting dominates complexity, linear scan is minor [OK]
- Assuming nested loops cause O(n*m)
- Ignoring sorting cost
- Confusing linear scan with quadratic
Solution
Step 1: Identify furthest_jump calculation
furthest_jump = pos + nums[pos] can exceed array bounds, causing range() to go out of range or runtime error.Step 2: Check impact
Without min(pos + nums[pos], n - 1), code may attempt invalid indices, causing incorrect behavior or crashes.Final Answer:
Option C -> Option CQuick Check:
Bounding furthest_jump by n-1 prevents out-of-range errors [OK]
- Forgetting to limit furthest_jump to n-1
- Incrementing jumps incorrectly
- Missing visited set usage
Solution
Step 1: Identify sorting cost
Sorting n trains by arrival time costs O(n log n).Step 2: Analyze heap operations
Each train causes at most one push and one pop on the heap, each O(log n), so total O(n log n).Final Answer:
Option C -> Option CQuick Check:
Sorting + heap operations dominate complexity [OK]
- Assuming O(n) ignoring sorting and heap costs
- Confusing heap size k with n for complexity
- Mistaking nested loops for optimal approach complexity
Solution
Step 1: Understand the new constraint
Allowing multiple transactions per day does not change the fact that profit comes from positive price differences.Step 2: Check if algorithm needs change
Summing all positive consecutive differences already accounts for all profitable transactions, including multiple per day.Final Answer:
Option B -> Option BQuick Check:
Algorithm already sums all positive increments, no modification needed [OK]
- Adding zero or negative differences incorrectly
- Overcomplicating with DP when greedy suffices
- Thinking multiple transactions per day require new logic
