The best run: Kadane's algorithm and the best day to sell
🌍 In real life. A small shop writes down each day's profit or loss: +2, −5, +3, −1, +4, −6, +2. The owner asks: "which stretch of days in a row made the most money?" And a farmer watching the price of rice wants to know the most they could have made by buying on one day and selling on a later one.
There are about n²/2 stretches to try. Both questions are answered in one pass by keeping just one number about "the best that ends today". That is the smallest dynamic program there is: Kadane's algorithm (LeetCode 53) and the stock problem (LeetCode 121).
The idea in one sentence: the best run that ends at today is either today alone or yesterday's best run plus today, cur = max(x, cur + x), and the answer is the best cur seen on any day.
Its words:
- subarray: a run of items next to each other
- cur: the best sum of a run that ends exactly at the current item; this is the DP state
- best: the best
curseen so far, the answer - restart: when
cur + x < x, the run so far only drags x down, so a new run starts at x
Step by step, for 2, −5, 3, −1, 4, −6, 2:
- Start:
cur = best = 2. - −5:
max(−5, 2 − 5) = −3. Best stays 2. - 3:
max(3, −3 + 3) = 3: the old run only hurts, so start again at 3. Best 3. - −1 then 4: 2, then 6. Best 6: the run 3, −1, 4.
- −6 then 2: 0, then 2. Best stays 6.
Why it is correct. Every run ends somewhere. The best run ending at item i either is item i alone or continues the best run ending at i − 1 (if a better run ended at i − 1, using it would give a better run at i). So cur is right for every i, and the answer, the best of all of them, is best. This is a 1D DP (Lesson 57.4) whose table is thrown away as it goes: only the last value is ever read.
The best day to sell. Selling on day j, the best you can do is buy at the cheapest price before it. So walk the prices once, keeping the lowest price so far, and at each day compare "sell today" with the best so far. (It is Kadane in disguise: the profit of buying on day i and selling on day j is the sum of the daily changes between them, so the best trade is the best run of daily changes.)
What it costs, by counting. One pass, a constant amount of work per item: O(n) time and O(1) memory. Trying every stretch is O(n²), and adding each one up from scratch O(n³).
def max_subarray(nums):
best = cur = nums[0] # cur: the best run that ends here
for x in nums[1:]:
cur = max(x, cur + x) # extend the run, or start again at x
best = max(best, cur)
return best
def max_profit(prices):
lowest, best = float("inf"), 0
for p in prices:
lowest = min(lowest, p) # the cheapest day to buy so far
best = max(best, p - lowest) # selling today after that day
return best
print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]), max_subarray([-3, -1, -2]))
print(max_profit([7, 1, 5, 3, 6, 4]), max_profit([7, 6, 4, 3, 1]))Mistakes and edge cases.
- Starting at 0.
best = cur = 0answers 0 for[-3, -1, -2], a run of no days, which isn't allowed. Start from the first item. - Resetting to 0 instead of x.
cur = max(0, cur + x)works only if an empty run counts; then a list of losses gives 0. - Selling before buying. Update
lowestbefore comparing, so a day's price is never paired with a later, cheaper one. - An empty list.
nums[0]raisesIndexError: list index out of range; decide what an empty input should give. - Wanting the run itself. Remember where the current run started and copy it into
best_start,best_endwheneverbestimproves.
Quiz
What does this print?
def max_subarray(nums): best = cur = nums[0] # cur: the best run that ends here for x in nums[1:]: cur = max(x, cur + x) # extend the run, or start again at x best = max(best, cur) return best print(max_subarray([5, -9, 6, -2, 3]), max_subarray([4, -1, 2]))At an item x, when does Kadane's algorithm start a new run instead of extending the old one?
- When the best run ending just before is negative, so cur + x < x
- When x is negative
- Never: it always extends
What does this print?
def max_profit(prices): lowest, best = float("inf"), 0 for p in prices: lowest = min(lowest, p) # the cheapest day to buy so far best = max(best, p - lowest) # selling today after that day return best print(max_profit([2, 4, 1, 7]), max_profit([9, 9, 9]))max_subarray([-3, -1, -2]) should be -1, but this gives 0. Which line is wrong?
def max_subarray(nums): best = cur = 0 for x in nums: cur = max(x, cur + x) best = max(best, cur) return best
Coding tasks
Write
max_subarray(nums): the biggest sum of a run of one or more items next to each other, in O(n). The list is never empty.Write
max_profit(prices): the most you can make by buying on one day and selling on a later day; 0 if no trade makes money.