TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › Choosing the State: Weighted Intervals and Increasing Subsequences

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 Θ(n2)\Theta(n^2) down to Θ(nlg⁡n)\Theta(n \lg n).

Weighted interval scheduling

A studio rents out one recording room. Requests arrive as intervals [si,fi)[s_i, f_i) with a payment viv_i; 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 2n2^n values. The fix is to sort by finish time and number the requests 1..n1..n in that order. Then let p(j)p(j) be the largest index i<ji < j whose request finishes no later than request jj starts (p(j)=0p(j) = 0 if there is none). Every request compatible with jj that comes before it in the order is among 1..p(j)1..p(j), so the state shrinks to a single number, a prefix of the sorted list:

OPT(0)=0,OPT(j)=max⁡(OPT(j−1), vj+OPT(p(j))).\mathrm{OPT}(0) = 0, \qquad \mathrm{OPT}(j) = \max\bigl(\mathrm{OPT}(j - 1),\ v_j + \mathrm{OPT}(p(j))\bigr).

Either the best schedule of the first jj requests skips request jj, or it takes it, and then the rest is the best schedule of the requests that end before jj begins. The values p(j)p(j) come from a binary search over the sorted finish times, so the whole algorithm is O(nlg⁡n)O(n \lg n): sorting, nn binary searches and a linear DP.

python · try it yourself
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 p(j)p(j)? Because the finish times are sorted, it counts the requests whose finish time is at most sjs_j, and those are exactly the requests 1..p(j)1..p(j). (Request jj itself is never counted, since fj>sjf_j > s_j.)

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 a1,…,ana_1, \ldots, a_n, 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 ii", with length L[i]L[i]. Its previous element is some aj<aia_j < a_i with j<ij < i:

L[i]=1+max⁡{ L[j]:j<i, aj<ai },with the max of nothing equal to 0,L[i] = 1 + \max\{\, L[j] : j < i,\ a_j < a_i \,\}, \qquad \text{with the max of nothing equal to } 0,

and the answer is max⁡iL[i]\max_i L[i]. The state is one number, but each state looks at all earlier positions, so the time is Θ(n2)\Theta(n^2).

python · try it yourself
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 kk, what is the smallest value that can end an increasing subsequence of length kk among the elements seen so far? Call it tail[k]\mathit{tail}[k]. A small tail is better than a large one, since more future elements can extend it.

Invariant: tail[1]<tail[2]<⋯<tail[ℓ]\mathit{tail}[1] < \mathit{tail}[2] < \cdots < \mathit{tail}[\ell], where ℓ\ell is the length of the LIS so far. (If tail[k+1]≤tail[k]\mathit{tail}[k+1] \le \mathit{tail}[k], the subsequence of length k+1k + 1 ending at tail[k+1]\mathit{tail}[k+1] would contain a subsequence of length kk ending at an even smaller value, contradicting the definition of tail[k]\mathit{tail}[k].)

When a new element xx arrives, it can extend every subsequence whose tail is less than xx. Because the tails are sorted, the longest such subsequence is found by binary search: find the first kk with tail[k]≥x\mathit{tail}[k] \ge x. Then xx becomes the new tail[k]\mathit{tail}[k] (it ends a length-kk subsequence with a smaller tail than before), or, if no such kk exists, xx extends the longest subsequence and ℓ\ell grows by one. The invariant is preserved, every step costs O(lg⁡n)O(\lg n), and the total is Θ(nlg⁡n)\Theta(n \lg n).

python · try it yourself
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 2n2\sqrt{n} (a famous theorem of Vershik-Kerov and Logan-Shepp). The approach is slow: 220,000≈2832\sqrt{20{,}000} \approx 283, and the measured 273 is lower by a correction of order n1/6n^{1/6}.

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 xx". The program computes the length only, for the example and for a long pseudo-random sequence.

cpp · try it yourself
#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 Θ(n2)\Theta(n^2) state and then with tails.

Test yourself

In weighted interval scheduling, why are the requests sorted by finish time first?

  1. So that greedy works
  2. So that the requests compatible with jj and earlier than it form a prefix 1..p(j)1..p(j), making the state a single index
  3. To make the binary search unnecessary
  4. Because payments increase with finish time

In the Θ(nlg⁡n)\Theta(n \lg n) LIS algorithm, which property of the tails array makes binary search possible?

  1. It is a subsequence of the input
  2. It is strictly increasing
  3. It never changes after an element is written
  4. It has length n\sqrt{n}

Processing 5, 1, 6, 2, 3 with the tails method, what is tails at the end?

  1. [1, 2, 3]
  2. [5, 6]
  3. [1, 6, 3]
  4. [1, 2, 6]