Bird
Raised Fist0

Given the following code implementing the peak-valley approach, what is the output for prices = [7,1,5,3,6,4]?

easy🧾 Code Trace Q3 of Q15
Greedy Algorithms - Best Time to Buy and Sell Stock II
Given the following code implementing the peak-valley approach, what is the output for prices = [7,1,5,3,6,4]?
A8
B5
C6
D7
Step-by-Step Solution
Solution:
  1. Step 1: Trace first valley and peak

    Valley at price 1 (index 1), peak at price 5 (index 2), profit += 4
  2. Step 2: Trace second valley and peak

    Valley at price 3 (index 3), peak at price 6 (index 4), profit += 3
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    4 + 3 = 7 total profit [OK]
Quick Trick: Sum peak-valley differences carefully [OK]
Common Mistakes:
MISTAKES
  • Off-by-one in loops
  • Missing last peak
  • Adding negative differences
Trap Explanation:
PITFALL
  • Candidates often miss last peak or miscalculate indices causing wrong profit.
Interviewer Note:
CONTEXT
  • Tests ability to trace greedy peak-valley code on typical input.
Master "Best Time to Buy and Sell Stock II" 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