Bird
Raised Fist0

Examine the following code snippet for the peak-valley approach. Which line causes incorrect profit calculation?

medium🐛 Buggy Code Q7 of Q15
Greedy Algorithms - Best Time to Buy and Sell Stock II
Examine the following code snippet for the peak-valley approach. Which line causes incorrect profit calculation?
def maxProfit(prices):
    i = 0
    profit = 0
    while i < len(prices) - 1:
        while i < len(prices) - 1 and prices[i] >= prices[i+1]:
            i += 1
        valley = prices[i]
        while i < len(prices) - 1 and prices[i] <= prices[i+1]:
            i += 1
        peak = prices[i]
        profit += peak - valley
    return profit
AAdding peak - valley to profit without checking i bounds
BAssigning valley after the first while loop
CLine incrementing i inside the second while loop
DLine incrementing i inside the first while loop
Step-by-Step Solution
Solution:
  1. Step 1: Review loop conditions

    Loops correctly find valleys and peaks by moving index i.
  2. Step 2: Check profit calculation

    Adding peak - valley assumes i is valid, but if i reaches end, peak may be out of range.
  3. Step 3: Identify bug

    Profit addition occurs without verifying i is within array bounds, causing incorrect calculation or error.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Ensure i is valid before using prices[i] [OK]
Quick Trick: Check array bounds before profit addition [OK]
Common Mistakes:
MISTAKES
  • Assuming loops always end with valid i
  • Ignoring edge cases with single element arrays
  • Not validating index before accessing prices
Trap Explanation:
PITFALL
  • Profit calculation without bounds check can cause errors
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle bugs in iterative code
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