Bird
Raised Fist0

Given the following code implementing the optimal wiggle subsequence algorithm, what is the output for input nums = [1, 7, 4, 9, 2, 5]?

easy🧾 Code Trace Q3 of Q15
Greedy Algorithms - Wiggle Subsequence
Given the following code implementing the optimal wiggle subsequence algorithm, what is the output for input nums = [1, 7, 4, 9, 2, 5]?
A5
B3
C4
D6
Step-by-Step Solution
Solution:
  1. Step 1: Trace loop iterations

    Differences: 7-1=6(+), 4-7=-3(-), 9-4=5(+), 2-9=-7(-), 5-2=3(+). Each alternation increments count.
  2. Step 2: Count increments

    Initial count=1, increments at each alternation -> final count=6.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    All differences alternate sign, count matches input length [OK]
Quick Trick: Count increments on sign changes in differences [OK]
Common Mistakes:
MISTAKES
  • Off-by-one counting
  • Ignoring first element in count
Trap Explanation:
PITFALL
  • Candidates often forget to initialize count=1 or mishandle last_diff updates.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute greedy code and track state variables.
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