Bird
Raised Fist0

Consider the following Python function implementing the optimal wiggle subsequence algorithm. What is the value of count after the loop finishes when the input is [1, 5, 4]?

easy🧾 Code Trace Q12 of Q15
Greedy Algorithms - Wiggle Subsequence
Consider the following Python function implementing the optimal wiggle subsequence algorithm. What is the value of 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
A2
B3
C1
D0
Step-by-Step Solution
Solution:
  1. 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=-1
  2. Step 2: Final count value

    After loop, count=3, which is the length of the longest wiggle subsequence.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Count increments twice for valid wiggles [OK]
Quick Trick: Count increments on sign change of diff from last_diff
Common Mistakes:
MISTAKES
  • Off-by-one counting
  • Ignoring initial count=1
  • Not updating last_diff correctly
Trap Explanation:
PITFALL
  • Some think count stays 1 or increments incorrectly due to sign checks.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute code and track variable updates precisely.
Master "Wiggle Subsequence" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes