The problem, in one line. Given a price for each day, pick one day to buy and a later day to sell for the biggest gain, or report 0 if every trade loses money. LeetCode 121.
The tell. Two positions where one must come before the other, and you want the best gap between them. That is a left end and a right end that only move forward.
The wrong first idea
Try every buy day against every later sell day.
best = 0
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
best = max(best, prices[j] - prices[i])
Correct, and it passes small tests. It looks at every pair, which is n times n over two. A year of minute prices is about 500,000 numbers, so that is over 100 billion pairs. The loop never needed most of them, because a sell day only cares about the cheapest day behind it.
The invariant
Let left be the buy day and right be today. Walk right forward one day at a time. If today is cheaper than the buy day, today becomes the better buy day, so left jumps to right. Otherwise today is a possible sell day.
prices 7 1 5 3 6 4
right=1 1 < 7, left jumps to day 1
right=2 5 - 1 = 4
right=4 6 - 1 = 5 best so far
The sentence that stays true every step: left is the cheapest day at or before right. That is why one pass is enough, and why selling can never happen before buying.
The solution
def max_profit(prices):
left, best = 0, 0
for right in range(1, len(prices)):
if prices[right] < prices[left]:
left = right # a cheaper buy day: the window restarts here
best = max(best, prices[right] - prices[left]) # sell today against the cheapest day behind
return best
print(max_profit([7, 1, 5, 3, 6, 4]))
print(max_profit([7, 6, 4, 3, 1]))
print(max_profit([2, 4, 1]))
5
0
2
func maxProfit(prices []int) int {
left, best := 0, 0
for right := 1; right < len(prices); right++ {
if prices[right] < prices[left] {
left = right // a cheaper buy day: the window restarts here
}
if p := prices[right] - prices[left]; p > best { // sell today against the cheapest day behind
best = p
}
}
return best
}
Same three calls print 5, 0, 2.
Complexity
- Time O(n):
rightvisits each day once andleftnever moves backward. - Space O(1): two indexes and a best.
Traps
- Taking the highest price minus the lowest price. On
[2, 4, 1]that gives 3, but the 1 comes after the 4, so the answer is 2. - Moving
lefton any one-day drop instead of a new low. On[5, 1, 4, 2, 6]the drop to 2 movesleftand loses the buy at 1, so it returns 4 instead of 5. - Letting
beststart below 0. On[7, 6, 4, 3, 1]the answer is 0, because you are allowed not to trade.
Next in the ladder
Longest Substring Without Repeating Characters stops tracking a number between the two ends and starts tracking a rule: the window may grow until the rule breaks, then the left end must move.