iq.lab
Python starts when a code cell comes near or you run one
12 Dynamic programming

Lesson 4 of 5

Choices with a budget

Many interview problems hand you items to take or leave under a limit. A table of the best answer for every budget compares every choice without listing them, and small changes to it solve equal-sum splits and coin combinations. A second table, one cell per place a subsequence can end, finds the longest increasing subsequence.

About 2 hours, with the 3 problems worked in it
By the end you can
  • Fill a 0/1 knapsack table and say in words what each cell means

  • Keep one row instead of the whole table, walking downward when each item is used once and upward when it can repeat

  • Turn that row into a yes or no (equal-sum split) or a count (coin combinations), with the loops in the order that counts each combination once

  • Find the longest increasing subsequence in O(n2) by fixing where each subsequence ends

  • Describe the O(n log n) tails idea for the scale follow-up

Tonight's batch window has 5 free hours, and three backfill jobs are waiting. The cluster runs one job at a time. Job A takes 4 hours and repairs 7 dashboards. Job B takes 3 hours and repairs 5. Job C takes 2 hours and repairs 3. Each job runs once or not at all. Which jobs should run?

The tempting answer is to run the biggest job first. A repairs 7 dashboards, and the hour left over fits nothing: 7 in total. Ranking by dashboards per hour picks A as well (1.75 per hour, against about 1.67 for B and 1.5 for C). But B and C together take exactly 5 hours and repair 8. Both rules are greedy, like biggest coin first in coin change: they take what looks best right now and never revisit it. Here greedy loses because an early choice spent budget that a better combination needed.

The safe method compares every group. Each job is in or out, so 3 jobs give 23 = 8 groups and 30 jobs give 230, over a billion. A table compares them all without listing them, and small changes to that one table solve two interview classics: equal-sum splits and coin combinations. A third classic, the longest increasing subsequence, keeps the same in-or-out choice with a different table.

A table of items and capacity

How can a table compare every group without listing them? Start with the problem's name. It is the 0/1 knapsack problem: items, each with a weight and a value, and a bag (the knapsack) that holds a total weight of at most the capacity. "0/1" means each item is taken 0 times or 1 time. Our jobs are the items, hours are weights, dashboards are values, and the 5-hour window is the capacity.

Look at the last item and ask the only question about it: in or out? If it stays out, the answer is the best from the earlier items with the same capacity. If it goes in, the answer is its value plus the best from the earlier items in the capacity left over. Both are the same question about fewer items and some capacity, so a cell named by two numbers, how many items and how much capacity, can hold each answer.

A reminder of the five questions from the one-dimensional lesson: the state says in words what one cell means, the transition computes a cell from cells already filled, the base cases are the cells filled without reading any other cell, the answer is the cell that holds the result, and the order fills every cell after the cells it reads.

  • State: dp[i][w] is the best total value using only the first i items, with total weight at most w.
  • Transition: skip item i and keep dp[i - 1][w], or, if it weighs at most w, take it: its value plus dp[i - 1][w - weight]. Keep the bigger.
  • Base cases: row 0 (no items) and column 0 (no capacity) are all 0.
  • Answer: the bottom-right cell, dp[n][capacity], where n is the number of items.
  • Order: row by row from the top. Every cell reads only the row above, so that row is always complete.

Item i sits at position i − 1 in the lists, because row 0 means "no items yet". The table below fills the batch-window example one cell at a time. Rows are the jobs considered so far (item 1 is job A), and columns are the hours, 0 to 5. The blue cell is being filled, amber outlines and arrows mark the cells it reads, and the formula under the table shows the real numbers. Before you step, guess dp[2][5]: the best from jobs A and B alone, with 5 hours.

Read the last cell as a sentence: the best with all three jobs and 5 hours is the better of "without job C" (7) and "job C plus the best from A and B in the 3 hours left" (3 + 5). Every cell is that sentence with other numbers. In code:

def best_value(weights, values, capacity):
    n = len(weights)
    dp = [[0] * (capacity + 1) for _ in range(n + 1)]   # row 0 and column 0 stay 0
    for i in range(1, n + 1):
        weight, value = weights[i - 1], values[i - 1]   # item i is at position i - 1
        for w in range(1, capacity + 1):
            dp[i][w] = dp[i - 1][w]                     # skip item i
            if weight <= w:                             # item i fits: try taking it
                dp[i][w] = max(dp[i][w], value + dp[i - 1][w - weight])
    return dp[n][capacity]

The cost grows with items times capacity, not with the number of groups. 30 jobs and a 5-hour window fill 31 × 6 = 186 cells, against over a billion groups. The catch: each capacity is a column number, so the weights must be whole numbers, and the capacity must be small enough for one column per value from 0 to the capacity.

Now fill a table yourself, on new numbers, one cell at a time.

On paperFill a knapsack table by hand

On paper, fill the 0/1 knapsack table for weights = [1, 2, 3], values = [6, 10, 12] and capacity = 5. Draw 4 rows (i = 0 to 3, the items considered) and 6 columns (w = 0 to 5, the capacity). Row 0 and column 0 are all 0.

Fill each row left to right. Skip keeps dp[i - 1][w]. Take, allowed when item i weighs at most w, gives its value plus dp[i - 1][w - weight]. Keep the bigger. What is dp[3][5]?

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.

dp[3][5]

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

One detail of the formula carries the rest of this lesson: which row the take option reads.

Quick checkWhy the row above?

The take option reads the row above: dp[i - 1][w - weight] + value. Why not the same row, dp[i][w - weight] + value?

Choose one answer, then check.

One row is enough, if you walk down

Does the table need all its rows? Each row of the table reads only the row above it. So keep one row, best, where best[w] is the best value within capacity w from the items handled so far, and update it in place for each new item. The only question is which cell to overwrite first. Try the obvious direction, smallest capacity first:

PredictOne row, walked upward

There is one item, with weight 2 and value 3, and one row of best values for capacities 0 to 4. This loop walks the capacities upward. Type exactly what it prints.

weight, value = 2, 3
best = [0, 0, 0, 0, 0]
for w in range(weight, 5):
    best[w] = max(best[w], best[w - weight] + value)
print(best)

Walking upward lets an item build on itself. best[w] reads best[w - weight], a cell to its left. Walk left to right and that cell has already been updated for the same item. Walk right to left, from the capacity down to the item's weight, and the cell you read still holds the old row. Capacities below the weight are never visited: the item does not fit there, so they keep the old value, which is the skip choice.

In Python the downward walk is range(capacity, weight - 1, -1). The third number, -1, makes range count down, and the stop, weight - 1, is left out as always, so the last w is weight. With capacity 5 and weight 4 it gives 5, then 4.

The trace runs the downward walk on the batch-window jobs, with arrows under best for w, the cell being updated, and rest, the cell it reads. Before you step, guess the final row.

Step throughOne row, walked downward
Step 1 of 42
Line 1 is about to run.
def best_value(weights, values, capacity):
best = [0] * (capacity + 1)
for i in range(len(weights)):
weight, value = weights[i], values[i]
for w in range(capacity, weight - 1, -1):
rest = w - weight
best[w] = max(best[w], value + best[rest])
return best[capacity]
Names
no names yet
Output
(nothing printed yet)

Downward means each item at most once. Keep the upward version in mind: later in this lesson it is exactly what we want.

Yes or no: can some numbers make a total?

What if the items have no values? Then the only question is whether some of them hit a total exactly. This is the subset sum problem: can a group of positive numbers, each used at most once, make exactly the target? It is a knapsack with the numbers as weights and the target as capacity, and each cell holds True or False instead of a best value.

  • State: can_make[s] is True when some group of the numbers walked so far makes s.
  • Transition: for a new number x, walk s down from the target to x. can_make[s] becomes True if it already was (skip x) or if can_make[s - x] is True (take x).
  • Base case: can_make[0] is True, because the empty group makes 0. Every other cell starts False.
  • Answer: can_make[target].

The row of booleans can also be a set: reachable, the sums you can make. For each number, build its new sums from the old set in a set of their own, new_sums, then merge them in: reachable |= new_sums adds every sum in new_sums to reachable (set union, like reachable.update(new_sums)). Building them separately does the job of the downward walk: a number is never added to a sum that already uses it. Here is the set growing for [3, 1, 5] and target 6:

Afterreachable (sums up to 6)
(start)0
30, 3
10, 1, 3, 4
50, 1, 3, 4, 5, 6

6 appears when the 5 arrives, built on the old sum 1: the group [1, 5]. The sums 3 + 5 = 8 and 4 + 5 = 9 are dropped, because with positive numbers, a sum above the target never comes back down. Now assemble the set version yourself.

Put in orderWhich sums can you make?

Put the lines in order to build can_make(nums, target): can some of the positive numbers in nums, each used at most once, add up to exactly target? The notebook is a set, reachable, of the sums that some group of the numbers walked so far makes. 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)
    • return target in reachable
    • if s + x <= target:
    • new_sums = set()
    • reachable = {0}
    • new_sums.add(s + x)
    • reachable |= new_sums
    • reachable = set()
    • for x in nums:
    • reachable.add(s + x)
    • def can_make(nums, target):
    • for s in reachable:

    Now the classic version: split a list into two groups with equal sums. Two groups with equal sums each make exactly half the total, so an equal split is subset sum with the target set to half. If one group makes half, the numbers left over make the other half, so finding one group is enough. An odd total cannot split at all. A list of booleans walked downward and a set both work.

    mediumDynamic programming, 1D target 25 min

    Split into two equal sums

    You get a list of positive integers nums. Decide whether you can split it into two groups with equal sums. Every number goes into exactly one of the two groups, and equal values at different positions are separate numbers.

    Return True if such a split exists and False if it does not.

    Example 1
    Inputnums = [3, 1, 5, 9, 2]OutputTrue

    The total is 20. The groups [9, 1] and [3, 5, 2] each sum to 10.

    Example 2
    Inputnums = [2, 4, 7]OutputFalse

    The total is 13, an odd number, so two equal halves are impossible.

    Example 3
    Inputnums = [3, 3, 4, 6]OutputFalse

    The total is 16, so one group must sum to 8. A single number is at most 6, any two make 6, 7, 9 or 10, and any three make at least 10.

    Constraints
    • 1 ≤ len(nums) ≤ 200

    • 1 ≤ nums[i] ≤ 100

    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.

    The halving was the whole trick: a question about one group replaced a question about two. The cost, O(n × half) where half is the total divided by 2, grows with the size of the numbers, not only with how many there are.

    Unlimited copies: walk up, and count

    What changes when an item can be used again, and the question is how many ways? Think of the one-row loop as having switches. Coin change II flips two at once: the cell holds a count, and each coin value can be used any number of times. Given an amount and some coin values, count the combinations that make the amount. A combination cares only about how many coins of each value it uses, so 1 + 2 and 2 + 1 are one combination.

    • State: ways[s] is the number of combinations of the coin values handled so far that make s.
    • Base case: ways[0] = 1. Making 0 has exactly one combination, the one with no coins. Without it, every count stays 0.
    • Transition: for a new value coin, a combination for s either uses no coin of this value, already counted in ways[s], or uses at least one. Take one of those coins away and what is left makes s - coin, and it may still hold more coins of this value. So ways[s] += ways[s - coin].

    Now the upward walk is what we want. Walking s upward, ways[s - coin] may already count combinations that use this coin, so one more coin of the same value can go on top. The trace counts the ways to make 4 with coins 1 and 2. Before you step, list them on paper.

    Step throughCounting coin combinations, one value at a time
    Step 1 of 32
    Line 1 is about to run.
    def count_combinations(amount, coins):
    ways = [0] * (amount + 1)
    ways[0] = 1
    for coin in coins:
    for s in range(coin, amount + 1):
    rest = s - coin
    ways[s] += ways[rest]
    return ways[amount]
    Names
    no names yet
    Output
    (nothing printed yet)

    The order of the loops matters as much as the direction. With coin values outside, all the 1s are placed before any 2, so every combination is built in one fixed order (its 1s, then its 2s) and counted once. Swap the loops and predict what happens:

    PredictThe loops swapped

    This version swaps the two loops: sums outside, coin values inside. Amount 3, coins [1, 2]. Type exactly what it prints.

    amount, coins = 3, [1, 2]
    ways = [1, 0, 0, 0]
    for s in range(1, amount + 1):
        for coin in coins:
            if coin <= s:
                ways[s] += ways[s - coin]
    print(ways)
    

    Sums outside counts orders; coin values outside counts combinations. Counting orders is a real problem too (LeetCode 377, Combination Sum IV), so read the question: is 1 + 2 the same as 2 + 1? In the problem below, it is. Fewest coins, in the one-dimensional lesson, put the amounts outside and was still right, because a minimum does not change when the same coins turn up again in another order; a count adds every one of them.

    mediumDynamic programming, 1D target 25 min

    Count coin combinations

    You get a whole number amount and a list coins of different coin values. You have as many coins of each value as you want. Return how many different combinations of coins add up to exactly amount.

    In a combination only the number of coins of each value matters, not their order: 1 + 2 and 2 + 1 are the same combination. When amount is 0 the answer is 1, the combination with no coins. When no combination works, the answer is 0.

    Example 1
    Inputamount = 4, coins = [1, 2, 3]Output4

    1 + 1 + 1 + 1, 1 + 1 + 2, 2 + 2 and 1 + 3. Counting orders as different would give 7, because 1 + 1 + 2 has three orders and 1 + 3 has two.

    Example 2
    Inputamount = 7, coins = [2, 4]Output0

    Every combination of 2s and 4s adds up to an even number, and 7 is odd.

    Example 3
    Inputamount = 0, coins = [5]Output1

    Using no coins makes 0.

    Constraints
    • 0 ≤ amount ≤ 5,000

    • 1 ≤ len(coins) ≤ 300

    • 1 ≤ coins[i] ≤ 5,000

    • The values in coins are all different.

    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.

    Two decisions changed the answer: the direction (upward, for reuse) and the nesting (values outside, for combinations). Now turn the switches the other way: a count, with each number used at most once.

    Code itCount the groups

    Write count_groups(nums, target): how many groups of the numbers add up to exactly target, using each number at most once? The numbers are positive. Equal values at different positions are different numbers, so [2, 2] has 2 groups that make 2. The empty group makes 0, so a target of 0 gives 1.

    This needs two switches from the lesson at once: a cell that counts, and a walk that uses each number at most once. Then press Watch it run.

    ⌘+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.

    Recap. Every problem so far keeps one row and walks the items in the outer loop. What changes is what a cell holds and which way the inner loop walks:

    ProblemThe cell holdsEach item is usedInner walk
    0/1 knapsackthe best valueat most oncedownward
    Equal-sum splityes or noat most oncedownward
    Count the groupsa countat most oncedownward
    Coin change IIa countany number of timesupward

    This module's practice bank has one more problem in this family: Signs to a target (LeetCode 494). It is one more turn of these switches. Before you code it, say what a cell holds and which way the inner loop walks.

    Subsequences: fix where it ends

    What if the limit is a rule about order instead of a budget? The last lesson took subsequences of strings. A subsequence of a list is the same idea: keep some items in their original order and drop the rest; the kept items do not have to be neighbors. In [2, 6, 3, 7, 4, 1], the items 2, 3, 4 form a subsequence, and so do 6, 7. Each item is kept or dropped, as in the knapsack, but the limit is a rule instead of a weight: in an increasing subsequence, each kept item must be bigger than the one kept before it. The longest increasing subsequence asks for the most items you can keep.

    The brute force tries all 2n keep-or-drop choices. For a table, ask what a subsequence needs in order to grow: a new item on the right must be bigger than its last item. So the fact that matters is where it ends.

    • State: ends_here[i] is the length of the longest strictly increasing subsequence that ends exactly at nums[i].
    • Transition: nums[i] stands alone (length 1), or follows any earlier nums[j] that is smaller, giving ends_here[j] + 1. Keep the largest.
    • Base case: every cell starts at 1.
    • Answer: the largest cell, because the longest subsequence can end anywhere.

    The widget fills these cells for [2, 6, 3, 7, 4, 1]. It calls the input values and our ends_here list dp. The blue cell is being filled, and amber outlines mark every earlier cell it reads. Before you step, guess the longest length, and whether the last cell holds it.

    Try one cell on a new list before writing the whole thing.

    Work it outOne cell of the subsequence table

    nums = [5, 1, 4, 2, 3]. ends_here[i] is the length of the longest strictly increasing subsequence that ends exactly at nums[i]. What is ends_here[4], the cell for the 3 at the end?

    ends_here[4]

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

    In code, the walk is two loops: i over every position, and inside it j over the positions before i. The classic slips are <= instead of < (equal items are not increasing), cells that start at 0 instead of 1, and returning the last cell instead of the largest. The puzzle below has one wrong line for each.

    Put in orderAssemble the subsequence table

    Put the lines in order to build longest_increasing(nums), the length of the longest strictly increasing subsequence. The notebook is ends_here, where ends_here[i] is the length of the longest one that ends exactly at nums[i]. Indentation is part of each line. Three lines do not belong: each is one of the classic slips.

    Your program

    Add lines from the list below, in order.

      Unused lines (some do not belong)
      • ends_here = [0] * len(nums)
      • for i in range(len(nums)):
      • return max(ends_here)
      • ends_here[i] = max(ends_here[i], ends_here[j] + 1)
      • if nums[j] < nums[i]:
      • return ends_here[-1]
      • for j in range(i):
      • def longest_increasing(nums):
      • if nums[j] <= nums[i]:
      • ends_here = [1] * len(nums)

      Now write it from a blank editor.

      mediumDynamic programming, 1D target 25 min

      Longest increasing subsequence

      You get a list of integers nums. A subsequence keeps some of the items in their original order and drops the rest; the kept items do not have to be neighbors.

      Return the length of the longest subsequence that is strictly increasing: every item is bigger than the one before it. Equal items do not count as increasing.

      Example 1
      Inputnums = [5, 2, 8, 6, 3, 6, 9, 7]Output4

      One longest is 2, 3, 6, 9, from positions 1, 4, 5 and 6. Another is 2, 3, 6, 7. None has 5 items.

      Example 2
      Inputnums = [4, 4, 4]Output1

      Equal items are not increasing, so the best is a single item.

      Example 3
      Inputnums = [1, 5, 2, 3]Output3

      1, 2, 3 skips the 5. The longest rising stretch of neighbors, [1, 5] or [2, 3], has only 2 items.

      Constraints
      • 1 ≤ len(nums) ≤ 2,500

      • -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.

      Fixing the end turned an unknown subsequence into one number per position, and each cell asks one question of every cell to its left. For the 2,500 items in the constraints, that is about 3 million pairs.

      The faster idea, for the follow-up

      What if there are 105 items? O(n2) is then about 5 billion pairs. The faster method keeps a different notebook: tails, where tails[k] is the smallest last item of any increasing subsequence of length k + 1 so far. A smaller last item is better, because more future items can follow it.

      tails stays sorted. Drop the last item of an increasing subsequence of length k + 2, and what is left has length k + 1 and ends lower, so each tail is smaller than the next. So a binary search finds each new item's place (module 6: halve the range at every step). bisect_left(tails, x), from Python's bisect module, returns the first position whose tail is at least x, or len(tails) when every tail is smaller. The new item replaces the tail at that position, or, when the position is len(tails), goes on the end, and the longest subsequence grows by one. The idea comes from patience sorting, a method named after the card game. Before you step, guess what tails holds at the end.

      Step throughThe tails list, for O(n log n)
      Step 1 of 31
      Line 1 is about to run.
      from bisect import bisect_left
      def lis_length(nums):
      tails = []
      for x in nums:
      k = bisect_left(tails, x)
      if k == len(tails):
      tails.append(x)
      else:
      tails[k] = x
      return len(tails)
      Names
      no names yet
      Output
      (nothing printed yet)

      Write the O(n2) table first, and keep the tails idea for the scale follow-up.

      Last, say it out loud, on the problem that opened the lesson.

      Say itSay it like you would in the room

      Back to the opening: three backfill jobs (4 hours for 7 dashboards, 3 hours for 5, 2 hours for 3) and a 5-hour window, each job run at most once. Explain to an interviewer, before typing, how you would choose the jobs. Say why taking the biggest job first is not enough, then cover the walk, the notebook, the promise and the cost.

      A few sentences first: 0 of 60 characters.

      Saved in this browser as you type.

      Next: How to find the state