Greedy Algorithms8 sections · 316 units
Open in Course

Stock II - Implementation

The code

Here is the solution:

function maxProfit(prices)
 profit := 0
 for i from 1 to length - 1
 if prices[i] > prices[i-1] then
 profit := profit + (prices[i] - prices[i-1])
 return profit

Time: O(n)O(n). Space: O(1)O(1).

Every positive difference means profit. If the price goes from 11 to 55, that is 44 profit. If it then goes to 33, you do not subtract (you already sold). If it goes from 33 to 66, that is 33 more profit. Total: 77.