Bird
Raised Fist0

What is the output of the peak-valley approach code when prices = [5] (only one day)?

medium🧾 Code Trace Q4 of Q15
Greedy Algorithms - Best Time to Buy and Sell Stock II
What is the output of the peak-valley approach code when prices = [5] (only one day)?
A5
BIndexError
C0
D-1
Step-by-Step Solution
Solution:
  1. Step 1: Check loop condition

    n=1, so i < n-1 -> 0 < 0 is false; loop body never executes.
  2. Step 2: Return profit

    Profit remains 0 as no transactions possible with single day.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Single day -> no profit -> 0 [OK]
Quick Trick: Single day means no transactions -> profit 0 [OK]
Common Mistakes:
MISTAKES
  • Expecting profit on single day
  • Index out of range errors
  • Misunderstanding loop conditions
Trap Explanation:
PITFALL
  • Candidates may expect error or profit when none occurs due to loop guard.
Interviewer Note:
CONTEXT
  • Tests boundary condition handling in code trace.
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