Greedy Algorithms8 sections · 316 units
Open in Course

Stock - Implementation

The code

Here is the solution:

function maxProfit(prices)
 if prices is empty then
 return 0
 minPrice := prices[0]
 maxProfit := 0
 for i from 1 to length - 1
 if prices[i] < minPrice then
 minPrice := prices[i]
 else
 profit := prices[i] - minPrice
 maxProfit := max(maxProfit, profit)
 return maxProfit

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

Each day, you either find a new minimum (update minPrice) or check if selling today is profitable (update maxProfit). One pass, two variables.