Lesson 1 of 2
Greedy choices
A greedy algorithm takes the best-looking choice at each step and never takes it back. It is fast, and it is right only when you can argue that no better answer was thrown away.
Say what makes an algorithm greedy, and try to break a greedy idea on tiny inputs before you trust it
Argue that a greedy choice is safe with an exchange argument in plain words
Find the best single trade with a running minimum
Find the largest sum of a run with Kadane's extend-or-restart rule
Decide whether a jump list can be crossed by tracking the farthest reach
Find the starting gas station in one pass by skipping every station a failure rules out
A cashier owes you 17 cents and has coins of 10, 5 and 1. Nobody at a till solves an optimization problem. They hand over the biggest coin that still fits, again and again, until nothing is owed.
That habit has a name. A greedy algorithm builds its answer one choice at a time, always takes the choice that looks best right now, and never goes back to change it. No table and no search: usually one pass, with a number or two in the notebook (the few values a walk writes down as it goes). Module 6 used two greedy rules already: the shipping check that fills each day's ship until the next package does not fit, and the rule that keeps the booking that ends first.
The catch is the phrase "looks best". Sometimes the best-looking move now is a mistake later, and a greedy algorithm never finds out. This lesson shows how to tell the two cases apart, then uses greedy on four interview classics where it is safe.
The greedy bet
What does "take the biggest coin that fits" look like as code? Walk the coins from biggest to smallest, and take each one as many times as it still fits. The notebook is amount, what is still owed, and used, the coins handed over so far. Before you step through, guess what used holds at the end.
def greedy_change(coins, amount):used = []for coin in coins:while amount >= coin:amount -= coinused.append(coin)return used
(nothing printed yet)Why is grabbing the biggest coin safe here? Take any handful that pays 17 with the fewest coins. It never holds five 1s: one 5 pays the same with four fewer coins. It never holds two 5s: one 10 pays the same with one fewer. So its 5s and 1s add up to at most 5 + 4 = 9, less than a 10. Its 10s must pay the rest and leave less than 10 owed, and for 17 that takes exactly one 10, the same as greedy. One level down, its 1s add up to at most 4, less than a 5, so the 7 still owed takes exactly one 5, again the same as greedy.
That is an exchange argument: take any best answer, swap part of it for the greedy choice, and show that the swap never makes it worse. If a best answer can always be changed to contain the greedy choice, taking that choice loses nothing. Module 6 made the same argument for the booking that ends first.
Here are the four answers this course asks of every algorithm. The promise is what stays true about the notebook after every step, and the cost uses Big O from module 2: O(k + c) means work that grows in step with k + c.
Now run the same code on different coins.
The same greedy_change runs with coins 4, 3 and 1 (listed biggest first) and an amount of 6. Type exactly what this prints.
def greedy_change(coins, amount):
used = []
for coin in coins:
while amount >= coin:
amount -= coin
used.append(coin)
return used
used = greedy_change([4, 3, 1], 6)
print(used, len(used))
When greedy fails
With coins 4, 3 and 1, biggest-first pays 6 as 4 + 1 + 1: three coins. Two 3s pay it with two. The 4 looked best, greedy took it, and nothing ever revisited that choice.
The exchange argument breaks here. The best way to pay 6 is 3 + 3, and no group of those coins adds up to exactly 4, so nothing in it can be traded for the 4. With 10, 5 and 1 that trade always exists: 5s and 1s worth 10 or more always hold a group worth exactly 10. Small amounts show where greedy first goes wrong:
| Amount | Biggest-first pays | Fewest coins |
|---|---|---|
| 1 | 1 (1 coin) | 1 |
| 2 | 1 + 1 (2 coins) | 2 |
| 3 | 3 (1 coin) | 1 |
| 4 | 4 (1 coin) | 1 |
| 5 | 4 + 1 (2 coins) | 2 |
| 6 | 4 + 1 + 1 (3 coins) | 2, as 3 + 3 |
| 7 | 4 + 3 (2 coins) | 2 |
Amount 6 is the smallest that breaks it. One input like that, a counterexample, is enough to sink a greedy idea. That is the habit to build: before you trust a greedy idea, try to break it on tiny inputs. When it breaks, use a method that tries every choice: module 12's coin change table, which began with this same trap, tries every coin as the last one for each amount and finds the two-coin answer for 6. It costs O(amount × coin types), not one pass, but it is always right.
With exactly one of these coin sets, biggest-first pays some amount with more coins than it needs. Which one? Try small amounts, and ask whether the smaller coins in a best handful can add up to a bigger coin or more.
Choose one answer, then check.
So far: greedy takes the best-looking choice and never undoes it, so trust it only when you can argue that nothing better is lost, usually with an exchange argument. The rest of this lesson is four problems where that argument holds.
Buy at the lowest price so far
A list holds a share's price on each day. You buy once and sell once, on a later day. What is the most profit? The profit is the sell price minus the buy price, and when no trade makes money the answer is 0. The brute force (the plain method that tries everything) checks every pair of days with the buy first: n(n − 1)/2 pairs, so O(n2) time, work that grows like n times n. The walk below is O(n).
Fix the day you sell, and the best day to have bought is the cheapest day before it. That is the greedy choice. The exchange argument: swap any other earlier buy day for the cheapest one, and the sell price stays the same while the buy price can only fall, so the profit never drops. So the walk needs two numbers: lowest, the cheapest price so far, and best, the largest profit so far.
The trace runs on the prices [4, 7, 1, 5, 3], days 0 to 4. Before you step through, guess the answer and the day on which best changes for the last time.
def max_profit(prices):lowest = prices[0]best = 0for price in prices:best = max(best, price - lowest)lowest = min(lowest, price)return best
(nothing printed yet)Profit first, then the minimum. Line 5 reads lowest before today's price can join it, so the buy price always comes from an earlier day. (Day 0 has no earlier day: lowest starts as its own price, which earns 0 and changes nothing.)
Try the walk on a list where the lowest price is a trap.
Using max_profit from the trace above, what does max_profit([8, 3, 6, 1, 3]) return? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now the full problem, edge cases included.
Change one rule and the greedy choice changes too: trade as often as you like, holding at most one share at a time.
Now you may make as many trades as you like, but you hold at most one share at a time: you must sell before you buy again. Write max_profit_many(prices), which returns the largest total profit, or 0 if no trade makes money.
A trade that buys on day a and sells on day b earns prices[b] - prices[a], which is the same as adding up every day-to-day change from day a to day b. Which changes are worth collecting?
raise NotImplementedError, then press Run tests. Each check says what it expects.Extend or restart: the largest sum of a run
A subarray (or run) is one or more neighboring items of a list, in order, with no gaps. In [3, -4, 2], [3, -4] is a run and [3, 2] is not. Which run has the largest sum? The brute force tries every start, then moves the end right one item at a time, adding each item to a running sum: n(n + 1)/2 runs, O(n2) time.
Ask a smaller question at each position: what is the best sum of a run that ends exactly here? Call it current. A run that ends at position i is either nums[i] alone, or a run that ends at i - 1 with nums[i] added on. The best of the second kind uses the best run that ends at i - 1, so:
current = max(nums[i], current + nums[i])
This is a greedy choice: extend the run behind you, or restart here. When the best run behind you adds up to less than zero, it can only drag nums[i] down, so we drop it for good. That is the exchange argument: cutting a negative stretch off the front of a run makes its sum bigger. A second number, best, keeps the largest current ever seen. This is Kadane's algorithm.
Before you step through [3, -4, 2, -1, 3], guess which run wins and what it adds up to.
def max_subarray(nums):current = nums[0]best = nums[0]for i in range(1, len(nums)):current = max(nums[i], current + nums[i])best = max(best, current)return best
(nothing printed yet)The same walk finds the smallest sum of a run, with min in place of max. Put it together.
Put the lines in order to build min_run(nums), which returns the smallest sum of any run (one or more neighboring items) in a non-empty list. It is Kadane's walk with min in place of max. Indentation is part of each line. Two lines do not belong.
Add lines from the list below, in order.
current = min(current, current + nums[i])current, smallest = 0, 0current = min(nums[i], current + nums[i])def min_run(nums):for i in range(1, len(nums)):current, smallest = nums[0], nums[0]smallest = min(smallest, current)return smallest
Now the full problem. Its tests include an all-negative list.
current is also a one-cell dynamic programming table: it answers "best run ending at i" from the answer at i - 1, the style of module 12. The greedy reading and the table reading give the same code.
This module's practice bank has the same walk with products: Largest product of a run (LeetCode 152). Multiplying by a negative number turns the smallest product into the largest, so its notebook keeps two numbers for the runs that end here, the largest product and the smallest. Try Kadane's rule on [2, -5, -2] before you open it.
So far: the stock walk carries the lowest price, and Kadane carries the best run ending here. Each keeps one number about the past and one about the answer.
The farthest you can reach
Each number in a list is the longest jump you may make from that position. Starting at position 0, can you reach the last position? From position i you may land anywhere from i + 1 to i + nums[i].
The tempting greedy is wrong: jump as far as you can. On [2, 3, 0, 0, 1] it jumps 2 places to position 2, which holds 0, and is stuck. A jump of 1 to position 1, then a jump of 3, reaches position 4.
The safe greedy never picks a jump at all. It keeps one number, farthest: the farthest position reachable from any position we can stand on. One number is enough because if you can reach position j, you can reach every position before it: the jump that landed on j could have stopped at any position it passed, and the same goes for the jumps before it. So the reachable positions are always one block, 0 up to farthest. If the walk arrives at a position beyond farthest, nothing reaches it, and the answer is False.
The two arrows show i, the position being visited, and farthest. Before you step through [2, 3, 0, 0, 1], guess the largest value farthest takes.
def can_jump(nums):farthest = 0for i in range(len(nums)):if i > farthest:return Falsefarthest = max(farthest, i + nums[i])return True
(nothing printed yet)Now a list where the walk stops early.
Run can_jump from the trace above on [2, 1, 1, 0, 5]. It returns False. What is farthest at the moment it returns? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
i > farthest is the only way to fail. A 0 hurts only when no earlier position jumps over it, and a 0 on the last position never matters, because you only need to land there. Now the full problem.
One failure rules out a whole stretch
Gas stations sit on a loop road. At station i you fill up gas[i] liters, and the drive to the next station, one leg of the loop, burns cost[i]. You start with an empty tank. From which station can you drive the whole loop without the tank going below zero? If several stations work, we want the smallest; if none does, the answer is -1. The brute force tries each start and drives around: up to n legs per start, O(n2).
Two observations make it one pass.
- Totals first. Every trip fills up at every station once and drives every leg once. If
sum(gas) < sum(cost), no start works. If the totals are enough, some start always works, and the walk below finds it. The problem's solution proves this; the walkthrough checks it by hand. - A failure rules out a stretch. Start at
start, and say the tank first goes below zero on the leg out of stationi. Take any stationkafterstart, up toi. The trip fromstartreachedkwith zero liters or more. Starting atkmeans arriving there with exactly zero, which is no better, so that trip also runs dry by the leg out of stationi. Every station fromstarttoifails, so the next candidate isi + 1, with an empty tank.
That is the greedy step: one candidate, only ever moved forward. The trace uses gas [3, 1, 4, 1, 3] and cost [2, 4, 2, 2, 1]. Each station's net gain, gas[i] - cost[i], is [1, -3, 2, -1, 2]. Before you step through, guess the station it returns.
def start_station(gas, cost):if sum(gas) < sum(cost):return -1start = 0tank = 0for i in range(len(gas)):tank += gas[i] - cost[i]if tank < 0:start = i + 1tank = 0return start
(nothing printed yet)Now trace one by hand. The tank lands on exactly zero in this one.
On paper, run start_station from the trace above on gas [2, 4, 1, 3] and cost [3, 2, 3, 1]. Write one row per station: the gain gas[i] - cost[i], the tank after it, and start. Which station does it return?
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Two details decide the edge cases. Reset start to i + 1, not i: station i was ruled out with the rest. And the test is tank < 0, not tank <= 0, because arriving with exactly zero liters is allowed. With <=, gas [2, 2, 2] and cost [2, 2, 2] would move start past every station and return 3, which is not a station at all. Every station works there, so the answer is 0. Now the full problem.
Is the greedy choice safe?
Every walk in this lesson made one choice per step and never undid it. What differed was the reason the choice was safe:
| Problem | The greedy choice | Why nothing better is lost |
|---|---|---|
| Change with 10, 5, 1 | the biggest coin that fits | smaller coins in a best answer add up to less than the next coin |
| Change with 4, 3, 1 | the biggest coin that fits | not safe: 3 + 3 beats 4 + 1 + 1 |
| One trade | buy at the lowest price so far | any other earlier buy day costs at least as much |
| Largest run | restart when the run behind is negative | a negative stretch in front only lowers the sum |
| Jump game | keep only the farthest reach | the reachable positions form one block from 0 |
| Gas station | after a failure, try i + 1 | every station from start to i fails too |
Before you trust a greedy idea, do three things out loud. Name the choice. Try to break it on tiny inputs, as 6 broke biggest-first with coins 4, 3 and 1. If it survives, say the exchange argument; if it breaks, try every choice, usually with dynamic programming. Two practice problems in this module pass that test: Jump game II, which counts the fewest jumps, and Cut a string by its letters, which cuts a string into as many pieces as possible so that each letter sits in one piece.
Last, say it the way you would in the room.
You have proposed the lowest-price-so-far walk for the one-trade stock problem. The interviewer asks: "Why is it safe to forget every earlier price except the lowest? And would biggest-coin-first be safe for making change with coins 1, 3 and 4?" Write what you would say, in a few plain sentences.
Saved in this browser as you type.