iq.lab
Python starts when a code cell comes near or you run one
13 Greedy and a little math

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.

About 2 hours 5 minutes, with the 4 problems worked in it
By the end you can
  • 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.

Step throughBiggest coin first
Step 1 of 24
Line 1 is about to run.
def greedy_change(coins, amount):
used = []
for coin in coins:
while amount >= coin:
amount -= coin
used.append(coin)
return used
Names
no names yet
Output
(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.

PredictBiggest coin first, 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:

AmountBiggest-first paysFewest coins
11 (1 coin)1
21 + 1 (2 coins)2
33 (1 coin)1
44 (1 coin)1
54 + 1 (2 coins)2
64 + 1 + 1 (3 coins)2, as 3 + 3
74 + 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.

Quick checkWhich coins break biggest-first?

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.

Step throughThe lowest price so far
Step 1 of 22
Line 1 is about to run.
def max_profit(prices):
lowest = prices[0]
best = 0
for price in prices:
best = max(best, price - lowest)
lowest = min(lowest, price)
return best
Names
no names yet
Output
(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.

Work it outOne trade on a new list

Using max_profit from the trace above, what does max_profit([8, 3, 6, 1, 3]) return? Type a whole number.

best

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Now the full problem, edge cases included.

easyGreedy choice target 15 min

Best day to buy and sell

A list prices holds the price of one share on each day: prices[0] on day 0, prices[1] on day 1, and so on. You may make one trade: buy one share on one day and sell it on a later day. The profit is the sell price minus the buy price.

Return the largest profit you can make. If no trade makes money, do not trade and return 0.

Example 1
Inputprices = [6, 2, 7, 1, 4]Output5

Buy on day 1 at 2, sell on day 2 at 7. The cheapest price, 1 on day 3, only leads to 4 - 1 = 3.

Example 2
Inputprices = [9, 7, 4, 3]Output0

Prices only fall, so every trade loses money. Do not trade.

Example 3
Inputprices = [5, 8, 2, 9]Output7

Buy on day 2 at 2, sell on day 3 at 9. Buying at 5 on day 0 makes at most 9 - 5 = 4.

Constraints
  • 1 ≤ len(prices) ≤ 105

  • 0 ≤ prices[i] ≤ 104

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

Change one rule and the greedy choice changes too: trade as often as you like, holding at most one share at a time.

Code itAs many trades as you like

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?

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says 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.

Step throughExtend or restart
Step 1 of 19
Line 1 is about to run.
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
Names
no names yet
Output
(nothing printed yet)

The same walk finds the smallest sum of a run, with min in place of max. Put it together.

Put in orderThe smallest sum of a run

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • current = min(current, current + nums[i])
    • current, smallest = 0, 0
    • current = 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.

    mediumGreedy choiceDynamic programming, 1D target 25 min

    Largest sum of a run

    A subarray, which we also call a run, is one or more neighboring items of a list, in order, with no gaps. In [4, -1, 2], both [4, -1] and [-1, 2] are subarrays, but [4, 2] is not.

    You get a list of integers nums. Every subarray of it has a sum. Return the largest of those sums. A subarray holds at least one item, so when every number is negative the answer is the largest single number, not 0.

    Example 1
    Inputnums = [2, -3, 4, -1, 2, -5, 3]Output5

    The subarray [4, -1, 2] adds up to 5. Crossing the -1 to reach the 2 pays off; crossing the -5 to reach the 3 does not.

    Example 2
    Inputnums = [-4, -2, -7]Output-2

    Every sum is negative, so the best is the largest single number.

    Example 3
    Inputnums = [5, -2, 6]Output9

    The whole list: the dip of -2 costs less than the 6 it reaches.

    Constraints
    • 1 ≤ len(nums) ≤ 105

    • -104 ≤ nums[i] ≤ 104

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Step throughTracking the farthest reach
    Step 1 of 21
    Line 1 is about to run.
    def can_jump(nums):
    farthest = 0
    for i in range(len(nums)):
    if i > farthest:
    return False
    farthest = max(farthest, i + nums[i])
    return True
    Names
    no names yet
    Output
    (nothing printed yet)

    Now a list where the walk stops early.

    Work it outWhere the reach runs out

    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.

    farthest

    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.

    mediumGreedy choice target 25 min

    Jump game

    You stand on position 0 of a list nums of non-negative integers. Each number is the longest jump you may make from its position: from position i you may move forward to any position from i + 1 up to i + nums[i]. A 0 means you cannot move on from there.

    Return True if some sequence of jumps reaches the last position, and False otherwise. You choose each jump's length, so a big number never forces you past the end.

    Example 1
    Inputnums = [2, 3, 0, 1, 4]OutputTrue

    Jump 1 place to position 1, then 3 places to position 4, the last one.

    Example 2
    Inputnums = [1, 2, 0, 0, 3]OutputFalse

    Positions 0 and 1 reach at most position 3. Positions 2 and 3 hold 0, so position 4 is out of reach.

    Example 3
    Inputnums = [0]OutputTrue

    You already stand on the last position.

    Constraints
    • 1 ≤ len(nums) ≤ 105

    • 0 ≤ nums[i] ≤ 105

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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 station i. Take any station k after start, up to i. The trip from start reached k with zero liters or more. Starting at k means arriving there with exactly zero, which is no better, so that trip also runs dry by the leg out of station i. Every station from start to i fails, so the next candidate is i + 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.

    Step throughMoving the start past a failure
    Step 1 of 25
    Line 1 is about to run.
    def start_station(gas, cost):
    if sum(gas) < sum(cost):
    return -1
    start = 0
    tank = 0
    for i in range(len(gas)):
    tank += gas[i] - cost[i]
    if tank < 0:
    start = i + 1
    tank = 0
    return start
    Names
    no names yet
    Output
    (nothing printed yet)

    Now trace one by hand. The tank lands on exactly zero in this one.

    On paperA tank that lands on zero

    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.

    start

    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.

    mediumGreedy choice target 25 min

    Gas station loop

    Gas stations sit on a loop road, numbered 0 to n - 1. Station i holds gas[i] liters of gas. Driving from station i to the next station, one leg of the trip, uses cost[i] liters, and the station after n - 1 is station 0.

    You pick a starting station and begin there with an empty tank that can hold any amount. At every station you reach, including the first, you take on all of its gas. The tank may never go below zero: you can leave station i only if, after taking on its gas, the tank holds at least cost[i] liters. Arriving at a station with exactly 0 liters is fine.

    Return the starting station from which you can drive the whole loop, back to that same station. If no station works, return -1. If several stations work, return the smallest number.

    Example 1
    Inputgas = [1, 5, 3, 2], cost = [3, 2, 2, 3]Output1

    From station 1 the tank holds 3, 4, 3 and 1 liters after the four legs. Station 0 fails at once: 1 liter cannot cover a leg of 3.

    Example 2
    Inputgas = [2, 2, 2], cost = [3, 2, 2]Output-1

    The loop needs 7 liters in all, and the stations hold only 6.

    Example 3
    Inputgas = [3, 1, 2], cost = [2, 2, 2]Output0

    From station 0 the tank holds 1, 0 and 0 liters after the legs, never below zero. Station 2 works too, and 0 is smaller.

    Constraints
    • n == len(gas) == len(cost), 1 ≤ n ≤ 105

    • 0 ≤ gas[i], cost[i] ≤ 104

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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:

    ProblemThe greedy choiceWhy nothing better is lost
    Change with 10, 5, 1the biggest coin that fitssmaller coins in a best answer add up to less than the next coin
    Change with 4, 3, 1the biggest coin that fitsnot safe: 3 + 3 beats 4 + 1 + 1
    One tradebuy at the lowest price so farany other earlier buy day costs at least as much
    Largest runrestart when the run behind is negativea negative stretch in front only lowers the sum
    Jump gamekeep only the farthest reachthe reachable positions form one block from 0
    Gas stationafter a failure, try i + 1every 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.

    Say itAnswer the rationale probe

    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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Bits and small math