Dynamic programming · 2 / 15 Theory

One-dimensional DP: change and subsequences

The simplest case is when the state is a single number: an amount, a position… The table is a list and each cell is computed from the previous ones.

def ways_combinations(amount, coins):
    ways = [0] * (amount + 1)
    ways[0] = 1
    for coin in coins:                       # first the coins...
        for total in range(coin, amount + 1):
            ways[total] += ways[total - coin]
    return ways[amount]

def ways_sequences(amount, coins):
    ways = [0] * (amount + 1)
    ways[0] = 1
    for total in range(1, amount + 1):         # ...or first the totals
        for coin in coins:
            if total >= coin:
                ways[total] += ways[total - coin]
    return ways[amount]

print(ways_combinations(4, [1, 2, 3]))        # 4   (1+1+1+1, 1+1+2, 2+2, 1+3)
print(ways_sequences(4, [1, 2, 3]))           # 7   (it also counts 2+1+1, 1+2+1...)

def longest_increasing(numbers):
    best = [1] * len(numbers)
    for i in range(len(numbers)):
        for j in range(i):
            if numbers[j] < numbers[i]:
                best[i] = max(best[i], best[j] + 1)
    return max(best)

print(longest_increasing([10, 9, 2, 5, 3, 7, 101, 18]))   # 4   (2, 3, 7, 18)
  • In ways to make change, the order of the loops decides what is counted: coins outside = combinations; totals outside = sequences.
  • In the longest increasing subsequence, best[i] is the length of the best one that *ends* at i; the answer is the maximum of the whole list, not the last value.
  • Before filling a table, write in one line what each cell means; almost all DP mistakes come from not having it clear.

You practice it in Ways to make change and Longest increasing subsequence.