Greedy Algorithms - Best Time to Buy and Sell Stock II
The following code attempts to implement the peak-valley approach but contains a subtle bug. Identify the line causing incorrect profit calculation.
def maxProfit(prices):
i = 0
profit = 0
n = len(prices)
while i < n - 1:
while i < n - 1 and prices[i] > prices[i + 1]:
i += 1
valley = prices[i]
while i < n - 1 and prices[i] < prices[i + 1]:
i += 1
peak = prices[i]
profit += peak - valley
return profit
