From brute force to the best answer, worked through
🌍 In real life. Karim writes down the price of onions at Kawran Bazar every morning. Looking back over the month, he asks: if I had bought one sack on one day and sold it on a later day, what was the most I could have made? The slow way tries every pair of days. The quick way notices that, for each selling day, only the cheapest earlier day matters.
The idea in one sentence: start with a brute force you can trust, find the work it repeats, keep one piece of information that removes the repeat, and check the fast version against the brute force on many small inputs.
Its words:
- brute force: try every possibility; slow, but easy to get right
- repeated work: the inner loop recomputes something the last pass already knew
- invariant: what a variable means after every step (here: the cheapest price so far)
The method, step by step:
- write the brute force and test it on the examples
- read its inner loop: what does it recompute every time?
- keep that in a variable (a minimum, a sum, a dict, a window)
- compare the fast and slow versions on hundreds of random small inputs
For the onion prices, the inner loop finds, for each selling day, the cheapest day before it: that minimum only ever needs the new price, so one pass is enough. A second worked problem, "the longest stretch of a word with no repeated letter", reads like this on the pattern map:
Why the fast versions are right. For profit: the best sale on day j pairs it with the cheapest day before j, and cheapest holds exactly that when day j is reached. For the word: if the letter at i was last seen inside the window, any window ending at i must start after it, and no window ending later can start earlier, so start only moves forward.
What it costs, by counting. For 100,000 days the brute force checks 4,999,950,000 pairs, O(n²); the fast version takes 100,000 steps, O(n) time and O(1) memory. The word problem drops the same way, from checking every stretch to one pass with a dict of at most 26 letters.
import random
def brute_profit(prices):
best = 0
for i in range(len(prices)): # buy on day i
for j in range(i + 1, len(prices)): # sell on a later day j
best = max(best, prices[j] - prices[i])
return best
def best_profit(prices):
best = 0
cheapest = float("inf")
for price in prices:
cheapest = min(cheapest, price) # the best day to have bought, so far
best = max(best, price - cheapest) # sell today
return best
print(best_profit([7, 1, 5, 3, 6, 4]), brute_profit([7, 1, 5, 3, 6, 4]))
random.seed(1)
for _ in range(300):
prices = [random.randint(1, 50) for _ in range(random.randint(0, 8))]
assert best_profit(prices) == brute_profit(prices), prices
print("300 random checks agree")Mistakes and edge cases.
- selling before buying:
max(prices) - min(prices)ignores the order of the days - prices that only fall: the best is 0, doing nothing, not a negative number
- no days, or one day: there is no sale, so 0
- trusting the fast version without a check: a random comparison with the brute force finds the bug a hand-made example misses
Quiz
What does this print?
def best_profit(prices): best = 0 cheapest = float("inf") for price in prices: cheapest = min(cheapest, price) # the best day to have bought, so far best = max(best, price - cheapest) # sell today return best print(best_profit([7, 1, 5, 3, 6, 4]), best_profit([7, 6, 4, 3, 1]))What does the brute force's inner loop keep recomputing?
- The cheapest price before each selling day
- The total of all prices
- The number of days
What does this print?
def longest_unique(s): last = {} # letter -> where it was seen last start = best = 0 for i, ch in enumerate(s): if ch in last and last[ch] >= start: start = last[ch] + 1 # the window must begin after the repeat last[ch] = i best = max(best, i - start + 1) return best print(longest_unique("pwwkew"), longest_unique("abba"))Why compare the fast version with the brute force on random small inputs?
- The brute force is easy to trust, so any difference points at a bug in the fast one
- To make the fast version faster
- Random inputs are what the judge uses
best_profit([3, 8, 1, 2]) gives 1 instead of 5. Which line is wrong?
def best_profit(prices): best = 0 cheapest = float("inf") for price in prices: cheapest = min(cheapest, price) best = price - cheapest return best
Coding tasks
Write
best_profit(prices):prices[i]is the price on day i. Buy on one day and sell on a later day; return the most you can make, or 0 if no sale makes money. Use one pass.Write
longest_unique(s): the length of the longest stretch ofs(letters next to each other) in which no letter repeats.