Choosing the State: Weighted Intervals and Increasing Subsequences
Every DP in this course so far came with an obvious set of subproblems: lengths of a rod, intervals of a chain, pairs of prefixes. In harder problems the first set of subproblems you think of is often too large, or does not quite close under the recurrence, and the art is in finding a better one. The description of a subproblem is called the state. This lesson works through two problems where the choice of state decides the running time: weighted interval scheduling, where sorting first makes a one-dimensional state possible, and the longest increasing subsequence, where a cleverer state brings down to .
Weighted interval scheduling
A studio rents out one recording room. Requests arrive as intervals with a payment ; two requests are compatible if their intervals do not overlap. Choose compatible requests with the largest total payment.
| request | A | B | C | D | E | F | G | H |
|---|---|---|---|---|---|---|---|---|
| start | 0 | 1 | 3 | 4 | 5 | 6 | 8 | 9 |
| finish | 4 | 3 | 7 | 6 | 9 | 10 | 11 | 12 |
| payment | 6 | 4 | 7 | 3 | 8 | 9 | 2 | 5 |
A first idea for the state is "the set of requests still available", which is closed under the recurrence but has values. The fix is to sort by finish time and number the requests in that order. Then let be the largest index whose request finishes no later than request starts ( if there is none). Every request compatible with that comes before it in the order is among , so the state shrinks to a single number, a prefix of the sorted list:
Either the best schedule of the first requests skips request , or it takes it, and then the rest is the best schedule of the requests that end before begins. The values come from a binary search over the sorted finish times, so the whole algorithm is : sorting, binary searches and a linear DP.
from bisect import bisect_right
requests = {"A": (0, 4, 6), "B": (1, 3, 4), "C": (3, 7, 7), "D": (4, 6, 3),
"E": (5, 9, 8), "F": (6, 10, 9), "G": (8, 11, 2), "H": (9, 12, 5)}
jobs = sorted(requests.items(), key=lambda kv: kv[1][1]) # by finish time
names = [name for name, _ in jobs]
start = [s for _, (s, f, v) in jobs]
finish = [f for _, (s, f, v) in jobs]
pay = [v for _, (s, f, v) in jobs]
n = len(jobs)
# p[j] for j = 1..n: how many requests finish by the time request j starts
p = [0] + [bisect_right(finish, start[j - 1]) for j in range(1, n + 1)]
OPT = [0] * (n + 1)
for j in range(1, n + 1):
OPT[j] = max(OPT[j - 1], pay[j - 1] + OPT[p[j]])
print(f"j = {j} ({names[j - 1]}, [{start[j - 1]}, {finish[j - 1]}), pays {pay[j - 1]}): "
f"p(j) = {p[j]}, OPT = max({OPT[j - 1]}, {pay[j - 1]} + {OPT[p[j]]}) = {OPT[j]}")
chosen, j = [], n
while j > 0:
if pay[j - 1] + OPT[p[j]] >= OPT[j - 1]: # taking j is optimal
chosen.append(names[j - 1]); j = p[j]
else:
j -= 1
print("best total", OPT[n], "with", sorted(chosen))j = 1 (B, [1, 3), pays 4): p(j) = 0, OPT = max(0, 4 + 0) = 4
j = 2 (A, [0, 4), pays 6): p(j) = 0, OPT = max(4, 6 + 0) = 6
j = 3 (D, [4, 6), pays 3): p(j) = 2, OPT = max(6, 3 + 6) = 9
j = 4 (C, [3, 7), pays 7): p(j) = 1, OPT = max(9, 7 + 4) = 11
j = 5 (E, [5, 9), pays 8): p(j) = 2, OPT = max(11, 8 + 6) = 14
j = 6 (F, [6, 10), pays 9): p(j) = 3, OPT = max(14, 9 + 9) = 18
j = 7 (G, [8, 11), pays 2): p(j) = 4, OPT = max(18, 2 + 11) = 18
j = 8 (H, [9, 12), pays 5): p(j) = 5, OPT = max(18, 5 + 14) = 19
best total 19 with ['A', 'E', 'H']
The reconstruction re-derives each choice from the table, as in Reconstructing an Optimal Solution. Why is bisect_right(finish, start[j - 1]) equal to ? Because the finish times are sorted, it counts the requests whose finish time is at most , and those are exactly the requests . (Request itself is never counted, since .)
Without the weights, all payments equal, the problem is activity selection, and a greedy algorithm solves it without any table: the subject of the Greedy Algorithms section. With weights, greedy rules fail, and this DP is the standard solution. The practice problem Weighted Job Scheduling is exactly this.
Longest increasing subsequence: the obvious state
Given a sequence , find a longest strictly increasing subsequence. For 3, 9, 4, 1, 8, 2, 6, 10, 5, 7 one answer is 3, 4, 6, 7. Is there a longer one?
The obvious state is "the longest increasing subsequence that ends at position ", with length . Its previous element is some with :
and the answer is . The state is one number, but each state looks at all earlier positions, so the time is .
a = [3, 9, 4, 1, 8, 2, 6, 10, 5, 7]
n = len(a)
L, prev, steps = [1] * n, [-1] * n, 0
for i in range(n):
for j in range(i):
steps += 1
if a[j] < a[i] and L[j] + 1 > L[i]:
L[i], prev[i] = L[j] + 1, j
best = max(range(n), key=lambda i: L[i])
seq, i = [], best
while i != -1:
seq.append(a[i]); i = prev[i]
print("L =", L)
print("an LIS:", seq[::-1], "length", L[best], " comparisons:", steps)L = [1, 2, 2, 1, 3, 2, 3, 4, 3, 4]
an LIS: [3, 4, 8, 10] length 4 comparisons: 45
A better state: the smallest possible tail
Here is a different question to keep track of while scanning left to right: for each length , what is the smallest value that can end an increasing subsequence of length among the elements seen so far? Call it . A small tail is better than a large one, since more future elements can extend it.
Invariant: , where is the length of the LIS so far. (If , the subsequence of length ending at would contain a subsequence of length ending at an even smaller value, contradicting the definition of .)
When a new element arrives, it can extend every subsequence whose tail is less than . Because the tails are sorted, the longest such subsequence is found by binary search: find the first with . Then becomes the new (it ends a length- subsequence with a smaller tail than before), or, if no such exists, extends the longest subsequence and grows by one. The invariant is preserved, every step costs , and the total is .
from bisect import bisect_left
def lis(a, verbose=False):
tails, tail_idx = [], [] # tails[k]: smallest tail of a length-(k+1) subsequence; tail_idx: its position
prev = [-1] * len(a)
for i, x in enumerate(a):
k = bisect_left(tails, x) # first tail >= x (strictly increasing: equal values can't extend)
if k == len(tails):
tails.append(x); tail_idx.append(i)
else:
tails[k] = x; tail_idx[k] = i
prev[i] = tail_idx[k - 1] if k > 0 else -1
if verbose:
print(f"x = {x:2}: tails = {tails}")
seq, i = [], tail_idx[-1] if tail_idx else -1
while i != -1:
seq.append(a[i]); i = prev[i]
return seq[::-1]
print("LIS:", lis([3, 9, 4, 1, 8, 2, 6, 10, 5, 7], verbose=True))
import random
rng = random.Random(8)
big = [rng.randint(1, 10 ** 6) for _ in range(20000)]
print("length of an LIS of 20000 random numbers:", len(lis(big)))x = 3: tails = [3]
x = 9: tails = [3, 9]
x = 4: tails = [3, 4]
x = 1: tails = [1, 4]
x = 8: tails = [1, 4, 8]
x = 2: tails = [1, 2, 8]
x = 6: tails = [1, 2, 6]
x = 10: tails = [1, 2, 6, 10]
x = 5: tails = [1, 2, 5, 10]
x = 7: tails = [1, 2, 5, 7]
LIS: [1, 2, 5, 7]
length of an LIS of 20000 random numbers: 273
Read the trace: after 8 arrives, the tails are [1, 4, 8]. That does not mean 1, 4, 8 is a subsequence (the 1 comes after the 4); it means there is a length-1 subsequence ending in 1, a length-2 one ending in 4 (3, 4) and a length-3 one ending in 8 (3, 4, 8). Only the length of tails is guaranteed to be the answer; the actual subsequence comes from the prev links, recorded at the moment each element was placed. For random sequences the LIS length grows like (a famous theorem of Vershik-Kerov and Logan-Shepp). The approach is slow: , and the measured 273 is lower by a correction of order .
The new state is not a subproblem in the usual sense, a smaller instance of the same question. It is a summary of everything seen so far that is just rich enough to process the next element: the moral of this lesson. The same idea of a sorted array of "best ends" appears in the patience-sorting view of LIS and in the Hunt-Szymanski LCS algorithm, which reduces an LCS to an increasing-subsequence computation of this kind.
In C++
std::lower_bound is the binary search for "first element not less than ". The program computes the length only, for the example and for a long pseudo-random sequence.
#include <algorithm>
#include <cstdio>
#include <random>
#include <vector>
int lis_length(const std::vector<int>& a) {
std::vector<int> tails;
for (int x : a) {
auto it = std::lower_bound(tails.begin(), tails.end(), x);
if (it == tails.end()) tails.push_back(x);
else *it = x;
}
return static_cast<int>(tails.size());
}
int main() {
std::printf("example: %d\n", lis_length({3, 9, 4, 1, 8, 2, 6, 10, 5, 7}));
std::mt19937 rng(8);
for (int n : {1000, 100000, 1000000}) {
std::vector<int> a(n);
for (int& x : a) x = static_cast<int>(rng() % 1000000000u);
std::printf("n = %7d: LIS %5d\n", n, lis_length(a));
}
}example: 4
n = 1000: LIS 58
n = 100000: LIS 616
n = 1000000: LIS 1983
Practise the length version with Longest Increasing Subsequence, first with the state and then with tails.
Test yourself
In weighted interval scheduling, why are the requests sorted by finish time first?
- So that greedy works
- So that the requests compatible with and earlier than it form a prefix , making the state a single index
- To make the binary search unnecessary
- Because payments increase with finish time
In the LIS algorithm, which property of the tails array makes binary search possible?
- It is a subsequence of the input
- It is strictly increasing
- It never changes after an element is written
- It has length
Processing 5, 1, 6, 2, 3 with the tails method, what is tails at the end?
- [1, 2, 3]
- [5, 6]
- [1, 6, 3]
- [1, 2, 6]