Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

DP on Intervals, Trees & Subsets

When the subproblems are ranges, subtrees or sets.

Prefixes are the default subproblem, but many problems refuse them. The cheapest way to multiply a chain of matrices depends on where a range is split; the best guest list for a company party depends on who reports to whom; the shortest delivery route depends on which stops are already done. Make the subproblem a range, a subtree or a set, and the same recipe works.

What you’ll learn

  • Solve interval DPs with dp[i][j]\mathrm{dp}[i][j] over ranges, filled by increasing length: matrix-chain order in O(n3)O(n^3), the "last event" trick, and palindrome partitioning.
  • Solve tree DPs by combining children in post-order: maximum independent set, minimum vertex cover, subtree sizes and the diameter in O(n)O(n), and preview rerooting.
  • Solve bitmask DPs over subsets: Held–Karp's O(2nn2)O(2^n n^2) for the traveling salesman, assignment in O(2nn)O(2^n n), and submask enumeration in O(3n)O(3^n).
  • Recognize from a statement and its constraints whether the subproblems are ranges, subtrees or subsets, and avoid each family's classic bugs.

Intervals: split a range, solve both sides

Multiplying a p×qp\times q matrix by a q×rq\times r matrix takes pqrpqr scalar multiplications. Matrix products are associative, so a chain A B CA\,B\,C can be computed as (AB)C(AB)C or A(BC)A(BC), with the same result and very different costs. With AA of size 10×3010\times30, BB 30×530\times5 and CC 5×605\times60:

(AB)C: 10⋅30⋅5+10⋅5⋅60=4500,A(BC): 30⋅5⋅60+10⋅30⋅60=27000.(AB)C:\ 10\cdot30\cdot5+10\cdot5\cdot60=4500,\qquad A(BC):\ 30\cdot5\cdot60+10\cdot30\cdot60=27000.

Trying every parenthesization is hopeless: there are 42 for six matrices and about 1.8 billion for twenty. A prefix of the chain is the wrong subproblem too, since an optimal order may multiply the middle first. The right one is a range of matrices. This is the classic matrix-chain multiplication problem, and the first example of interval DP.

RangeCandidates (split after …)Best
ABAB, BCBC, CDCDone split each: 10⋅30⋅510\cdot30\cdot5, 30⋅5⋅6030\cdot5\cdot60, 5⋅60⋅105\cdot60\cdot101500, 9000, 3000
ABCABCafter AA: 0+9000+10⋅30⋅60=270000+9000+10\cdot30\cdot60=27000; after BB: 1500+0+10⋅5⋅60=45001500+0+10\cdot5\cdot60=45004500
BCDBCDafter BB: 0+3000+30⋅5⋅10=45000+3000+30\cdot5\cdot10=4500; after CC: 9000+0+30⋅60⋅10=270009000+0+30\cdot60\cdot10=270004500
ABCDABCDthree candidates: predict them below?
Four matrices with dimensions p=[10,30,5,60,10]p=[10,30,5,60,10]: AA is 10×3010\times30, BB 30×530\times5, CC 5×605\times60, DD 60×1060\times10. Every cell reads only shorter ranges, so the table is filled by increasing length.
Predict before you look

Finish the table: what is the least cost of computing ABCDABCD? Its three candidates split after AA, after BB and after CC.

Show the answer

5000

After AA: 0+4500+10⋅30⋅10=75000+4500+10\cdot30\cdot10=7500. After BB: 1500+3000+10⋅5⋅10=50001500+3000+10\cdot5\cdot10=5000. After CC: 4500+0+10⋅60⋅10=105004500+0+10\cdot60\cdot10=10500. The best is (AB)(CD)(AB)(CD) at 5000; the worst of the five parenthesizations costs 33000.

python
def matrix_chain(p):
    """Matrix i has shape p[i] x p[i+1]. Least number of scalar multiplications."""
    n = len(p) - 1
    cost = [[0] * n for _ in range(n)]       # cost[i][j]: best for A_i..A_j (inclusive)
    for length in range(2, n + 1):           # shorter ranges first
        for i in range(n - length + 1):
            j = i + length - 1
            cost[i][j] = min(cost[i][k] + cost[k + 1][j] + p[i] * p[k + 1] * p[j + 1]
                             for k in range(i, j))
    return cost[0][n - 1]

print(matrix_chain([10, 30, 5, 60, 10]))     # 5000: (AB)(CD)

Θ(n2)\Theta(n^2) states, O(n)O(n) splits each: O(n3)O(n^3) time in the worst case (exactly (n3−n)/6(n^3-n)/6 split evaluations) and Θ(n2)\Theta(n^2) space. Keep the best kk per cell to print the parenthesization.

Think about the last event

Some interval problems hide their split point. A row of numbers is removed one number at a time; removing xx earns (its current left neighbor) × x ×\times\,x\,\times (its current right neighbor), with an imaginary wall of value 1 at each end. Maximize the total.

Choosing the first removal is a dead end: after it, its two neighbors touch, and the two sides are no longer independent. Choose instead the last number kk removed strictly between positions ii and jj. While the numbers on its two sides are being removed, kk is still standing, so the left part only ever sees ii and kk as boundaries and the right part only kk and jj. When kk finally goes, its neighbors are exactly ii and jj.

dp[i][j]=max⁡i<k<j(dp[i][k]+dp[k][j]+bi bk bj),dp[i][i+1]=0\mathrm{dp}[i][j]=\max_{i<k<j}\Big(\mathrm{dp}[i][k]+\mathrm{dp}[k][j]+b_i\,b_k\,b_j\Big),\qquad \mathrm{dp}[i][i+1]=0
bb is the row with a 1 added at both ends, and dp[i][j]\mathrm{dp}[i][j] is the best total for the numbers strictly between positions ii and jj.
python
def best_removal(a):
    b = [1] + a + [1]                        # walls of value 1
    n = len(b)
    dp = [[0] * n for _ in range(n)]         # dp[i][j]: numbers strictly between i and j
    for gap in range(2, n):                  # j - i, shorter gaps first
        for i in range(n - gap):
            j = i + gap
            dp[i][j] = max(dp[i][k] + dp[k][j] + b[i] * b[k] * b[j]
                           for k in range(i + 1, j))   # k: the LAST one removed
    return dp[0][n - 1]

print(best_removal([2, 4, 3]))               # 33: remove 4 (24), then 2 (6), then 3 (3)

O(n3)O(n^3) time. A brute force over all n!n! removal orders agrees on random inputs.

Check your understanding

Why does the recurrence choose the number removed last in a range, rather than the one removed first?

  1. Removing the last number earns the most, so it decides the optimum
  2. The last number's neighbors are the range's fixed ends, so the parts on its two sides are independent subproblems
  3. Both choices give valid recurrences; "last" is merely faster
  4. So that the table can be filled by increasing length
Show the answer

B. The last number's neighbors are the range's fixed ends, so the parts on its two sides are independent subproblems

Until kk is removed it separates the two sides, so each side is solved on its own with fixed boundaries, and kk itself scores bibkbjb_ib_kb_j. After removing the first number, its neighbors become adjacent and the sides interact, so no recurrence over independent ranges exists.

Interval tables also serve as building blocks. To cut a string into the fewest palindromes, first fill pal[i][j]\mathrm{pal}[i][j] (s[i..j]s[i..j] is a palindrome iff s[i]=s[j]s[i]=s[j] and pal[i+1][j−1]\mathrm{pal}[i+1][j-1]), an O(n2)O(n^2) interval table, then run a prefix DP cuts[j]=min⁡{cuts[i]+1: pal[i][j−1]}\mathrm{cuts}[j]=\min\{\mathrm{cuts}[i]+1:\ \mathrm{pal}[i][j-1]\} over the O(n2)O(n^2) pairs. For "noonabbad" the answer is 3 pieces, noon | abba | d, so 2 cuts.

Trees: children first

On a rooted tree the natural subproblem is a subtree: the answer for vertex vv combines the answers of its children, and different children's subtrees share nothing. Any order that handles every child before its parent works, such as a post-order traversal or the reverse of a BFS order, and each edge is used a constant number of times: O(n)O(n) in all. This is tree DP.

Maximum independent set (the largest set of vertices with no edge inside, say employees invited without their direct boss). Keep two numbers per vertex: take[v]\mathrm{take}[v], the best in vv's subtree with vv chosen, and skip[v]\mathrm{skip}[v], the best with vv not chosen.

take[v]=wv+∑c child of vskip[c],skip[v]=∑c child of vmax⁡(take[c], skip[c])\mathrm{take}[v]=w_v+\sum_{c\ \text{child of}\ v}\mathrm{skip}[c],\qquad \mathrm{skip}[v]=\sum_{c\ \text{child of}\ v}\max\big(\mathrm{take}[c],\ \mathrm{skip}[c]\big)
If vv is chosen, no child may be; if it is not, each child is free to do whatever is best for its own subtree. The answer is max⁡(take[r],skip[r])\max(\mathrm{take}[r],\mathrm{skip}[r]) at the root rr.
Vertex (finishing order)DHIEBFJGCA
take\mathrm{take}1111311126
skip\mathrm{skip}0002300125
Unit weights on the tree above (edges A–B, A–C, B–D, B–E, C–F, C–G, E–H, E–I, G–J). The maximum independent set has 6 vertices, for example {A,D,F,G,H,I}\{A,D,F,G,H,I\}.
python
from collections import defaultdict

def max_independent_set(n, edges, root=0):
    adj = defaultdict(list)
    for u, v in edges:
        adj[u].append(v)
        adj[v].append(u)
    parent, order = [-1] * n, [root]
    for v in order:                          # BFS: the list grows while we scan it
        for c in adj[v]:
            if c != parent[v]:
                parent[c] = v
                order.append(c)
    take, skip = [1] * n, [0] * n            # unit weights: take[v] counts v itself
    for v in reversed(order):                # children before parents
        p = parent[v]
        if p >= 0:
            take[p] += skip[v]
            skip[p] += max(take[v], skip[v])
    return max(take[root], skip[root])

No recursion, so a path of 10510^5 vertices cannot overflow Python's call stack. O(n)O(n) time and space.

The same pattern computes many other things in one pass: subtree sizes (size[v]=1+∑csize[c]\mathrm{size}[v]=1+\sum_c\mathrm{size}[c]); the minimum vertex cover, which is the complement of a maximum independent set (here 10−6=410-6=4 vertices, such as {B,C,E,G}\{B,C,E,G\}); and the diameter, the longest path, which passes through some highest vertex vv and uses its two deepest child subtrees (here 6 edges, H–E–B–A–C–G–J).

Rerooting answers a question for every choice of root without nn separate passes. For the sum of distances from vv to all vertices, move the root from a vertex pp to its child cc: the size[c]\mathrm{size}[c] vertices in cc's subtree get one step closer, the other n−size[c]n-\mathrm{size}[c] one step farther, so ans[c]=ans[p]+n−2 size[c]\mathrm{ans}[c]=\mathrm{ans}[p]+n-2\,\mathrm{size}[c]. One pass computes the sizes and ans[root]\mathrm{ans}[\text{root}], a second pass pushes the answers down: O(n)O(n) for all roots.

Think first On the tree above (n=10n=10), the distances from B to all vertices sum to 19, and E's subtree {E,H,I}\{E,H,I\} has 3 vertices. What is the sum of the distances from E to all vertices?
  1. ans[E]=ans[B]+n−2 size[E]=19+10−6\mathrm{ans}[E]=\mathrm{ans}[B]+n-2\,\mathrm{size}[E]=19+10-6: E, H and I come one step closer (−3-3) and the other seven vertices move one step farther (+7+7). Counted directly: E is at distance 0; B, H, I at 1; A, D at 2; C at 3; F, G at 4; J at 5.

Subsets: bitmasks when n is about 20

In the traveling salesman problem a salesman starts at city 0, visits each of the other n−1n-1 cities once and returns, along the shortest tour. Brute force tries (n−1)!/2(n-1)!/2 tours. But the best way to continue a partial route depends only on which cities it has visited and where it stands, not on the order of the visits. A set of cities fits in the bits of one integer, a bitmask, so the states are pairs (set, last city): bitmask DP.

dp[S][j]=min⁡k∈S∖{j}(dp[S∖{j}][k]+d(k,j)),dp[{j}][j]=d(0,j),tour=min⁡j(dp[all][j]+d(j,0))\mathrm{dp}[S][j]=\min_{k\in S\setminus\{j\}}\Big(\mathrm{dp}[S\setminus\{j\}][k]+d(k,j)\Big),\qquad \mathrm{dp}[\{j\}][j]=d(0,j),\qquad \text{tour}=\min_j\big(\mathrm{dp}[\text{all}][j]+d(j,0)\big)
dp[S][j]\mathrm{dp}[S][j] is the length of the shortest path that starts at city 0, visits exactly the cities of SS (a set of cities other than 0) and ends at j∈Sj\in S. This is the Held–Karp algorithm, found independently by Bellman and by Held and Karp in 1962.
cpp
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;

// dp[S][j]: shortest path from city 0 through exactly the cities of S, ending at j.
// Cities 1..n-1 are stored as bits 0..n-2 of S.
long long held_karp(const vector<vector<long long>>& d) {
    int n = d.size(), m = n - 1;
    const long long INF = 1LL << 60;
    vector<vector<long long>> dp(1 << m, vector<long long>(m, INF));
    for (int j = 0; j < m; j++) dp[1 << j][j] = d[0][j + 1];
    for (int S = 1; S < (1 << m); S++)            // increasing S: every set after its subsets
        for (int j = 0; j < m; j++) {
            if (!(S >> j & 1) || dp[S][j] == INF) continue;
            for (int k = 0; k < m; k++)           // extend the path to an unvisited city k
                if (!(S >> k & 1)) {
                    int T = S | 1 << k;
                    dp[T][k] = min(dp[T][k], dp[S][j] + d[j + 1][k + 1]);
                }
        }
    long long best = INF;
    for (int j = 0; j < m; j++) best = min(best, dp[(1 << m) - 1][j] + d[j + 1][0]);
    return best;
}

int main() {
    vector<vector<long long>> d = {{0, 3, 4, 2, 7}, {3, 0, 4, 6, 3}, {4, 4, 0, 5, 8},
                                   {2, 6, 5, 0, 6}, {7, 3, 8, 6, 0}};
    printf("%lld\n", held_karp(d));               // 19
}

Adding a city to SS makes the integer larger, so increasing integer order handles every set after all of its subsets: a topological order for free. With n=20n=20 there are 219⋅19≈1072^{19}\cdot19\approx10^7 entries and about 2×1082\times10^8 extensions, fine in C++; brute force would need about 6×10166\times10^{16} tours.

Bitmask DPs often need only the set. To give nn workers nn jobs at least total cost, let best[mask]\mathrm{best}[\mathit{mask}] be the least cost of having workers 0,…,k−10,\dots,k-1 do the jobs in mask\mathit{mask}, where kk is the number of set bits (popcount): worker kk is always the next one to place, so no "last element" is needed, and the DP costs O(2nn)O(2^n n).

python
def assign(cost):
    """cost[i][j]: worker i does job j. Least total cost, each job done once. O(2^n * n)."""
    n = len(cost)
    best = [float('inf')] * (1 << n)    # best[mask]: workers 0..k-1 did the jobs in mask, k = popcount
    best[0] = 0
    for mask in range(1 << n):          # increasing order: every mask after its submasks
        i = bin(mask).count('1')        # the next worker to place
        if i == n:
            continue
        for j in range(n):
            if not mask >> j & 1:
                new = mask | 1 << j
                best[new] = min(best[new], best[mask] + cost[i][j])
    return best[(1 << n) - 1]

cost = [[2, 3, 4, 4], [1, 7, 7, 8], [1, 6, 9, 8], [2, 6, 1, 3]]
print(assign(cost))   # 12: jobs 3, 0, 1, 2; giving each worker the cheapest free job costs 18

For large nn the Hungarian algorithm solves assignment in O(n3)O(n^3). The bitmask DP shines when the cost of a job depends on which jobs came before, which the Hungarian algorithm cannot express.

Some transitions combine a set with any of its subsets, such as "close one more group, made of some of the remaining items". Enumerating the submasks of every mask (sub = (sub - 1) & mask) costs

∑mask2popcount(mask)=∑k=0n(nk)2k=3n,\sum_{\mathit{mask}}2^{\mathrm{popcount}(\mathit{mask})}=\sum_{k=0}^{n}\binom nk2^k=3^n,

because each element is either outside the mask, inside the submask, or inside the mask but not the submask. 316≈4.3×1073^{16}\approx4.3\times10^7 is fast; 320≈3.5×1093^{20}\approx3.5\times10^9 is not.

Think first A DP loops over every mask of n=15n=15 items and, for each mask, over all of its submasks. About how many (mask, submask) pairs does it visit?

315=14,348,907≈1.4×1073^{15}=14{,}348{,}907\approx1.4\times10^7: each item is outside the mask, in the submask, or in the mask only. That is far fewer than the 415≈1.1×1094^{15}\approx1.1\times10^9 pairs of arbitrary masks, but far more than the 215⋅15≈4.9×1052^{15}\cdot15\approx4.9\times10^5 steps of a DP that adds one item at a time.

Recognizing it

The subproblems' shape is usually visible in the statement and the constraints:

  • Ranges: "merge adjacent", "parenthesize", "remove from a row and score by the current neighbors", "cut a string into pieces", with nn up to about 500 (for O(n3)O(n^3)) or 5000 (for O(n2)O(n^2)). The state is dp[i][j]\mathrm{dp}[i][j], and the transition picks a split point or the last event inside the range.
  • Subtrees: a hierarchy, "each employee has one manager", "a network with no cycles", a tree with nn up to 10510^5–10610^6. A few numbers per vertex, combined from the children, in O(n)O(n).
  • Subsets: "visit every city", "assign each worker", "which items are already used", with nn at most about 20. The state is a mask, often with a last element: O(2nn)O(2^nn) or O(2nn2)O(2^nn^2).
Problem (in brief)Key ideaCost
Cheapest order to multiply a chain of matrices, or to merge adjacent piles when a merge costs the total sizedp[i][j]\mathrm{dp}[i][j] over a split pointO(n3)O(n^3)
Remove numbers from a row; each removal scores with its current neighborsThe last one removed between ii and jjO(n3)O(n^3)
Invite the most employees, never an employee together with their direct managertake/skip\mathrm{take}/\mathrm{skip} per vertexO(n)O(n)
Shortest closed route through n≤18n\le18 citiesHeld–Karp dp[S][j]\mathrm{dp}[S][j]O(2nn2)O(2^nn^2)
Fewest work sessions of length TT for n≤18n\le18 tasksdp[mask]\mathrm{dp}[\mathit{mask}] = (sessions, time used in the last one), minimized in that orderO(2nn)O(2^nn)
For the sessions problem, comparing pairs (sessions, last load) lexicographically is safe: fewer sessions are always better, and with equally many, a lighter last session leaves more room.
Check your understanding

n=16n=16 tasks with durations up to 10 hours must be scheduled into work sessions of at most 10 hours; a task cannot be split. You want the fewest sessions. Which approach fits?

  1. Interval DP over the tasks in input order
  2. Greedy: sort the tasks by duration and fill each session in turn
  3. Bitmask DP over the set of tasks done, keeping (sessions, hours used in the last session)
  4. A knapsack table over the 10 hours of one session
Show the answer

C. Bitmask DP over the set of tasks done, keeping (sessions, hours used in the last session)

Tasks may go in any order, so the state is the set of tasks already scheduled: 2162^{16} masks times 16 tasks to add, about 10610^6 steps. It is bin packing, which is strongly NP-hard in general but easy for n=16n=16.

Key takeaways

  • Interval DP: dp[i][j]\mathrm{dp}[i][j] over ranges, combining two shorter ranges at a split point (or around the last event), filled by increasing length; matrix-chain order costs O(n3)O(n^3).
  • Tree DP: a few numbers per vertex, combined from the children in post-order; maximum independent set uses take/skip\mathrm{take}/\mathrm{skip} and runs in O(n)O(n).
  • Bitmask DP: the state is a subset, often with a last element; Held–Karp solves the traveling salesman in O(2nn2)O(2^nn^2) for nn up to about 20.
  • The constraints point to the structure: n≤500n\le500 and "merge adjacent" for intervals, a hierarchy with nn up to 10510^5 or more for trees, and n≤20n\le20 with "which items are used" for bitmasks.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the matrix-chain table, cost[i][j]\mathrm{cost}[i][j] reads cost[i][k]\mathrm{cost}[i][k] and cost[k+1][j]\mathrm{cost}[k+1][j] for i≤k<ji\le k<j. Which filling order is valid?

  1. Row by row: i=0,1,…i=0,1,\dots, and jj increasing within a row
  2. By increasing length j−ij-i
  3. Column by column, jj decreasing
  4. Any order, since each cell is computed only once
Show the answer

B. By increasing length j−ij-i

Both cells read have strictly shorter ranges, so filling by increasing length guarantees they are ready. (Rows with ii decreasing and jj increasing also work.)

Question 2

In the tree DP for maximum independent set, which formula is right for skip[v]\mathrm{skip}[v], the best value in vv's subtree with vv not chosen?

  1. ∑cskip[c]\sum_c\mathrm{skip}[c]
  2. ∑ctake[c]\sum_c\mathrm{take}[c]
  3. ∑cmax⁡(take[c],skip[c])\sum_c\max(\mathrm{take}[c],\mathrm{skip}[c])
  4. max⁡ctake[c]\max_c\mathrm{take}[c]
Show the answer

C. ∑cmax⁡(take[c],skip[c])\sum_c\max(\mathrm{take}[c],\mathrm{skip}[c])

If vv is not chosen, each child may be chosen or not, independently of the others, so each child contributes the better of its two values.

Question 3

Held–Karp runs on n=20n=20 cities, with city 0 fixed as the start. Roughly how many table entries dp[S][j]\mathrm{dp}[S][j] are there, and how much work in total?

  1. About 19!/2≈6×101619!/2\approx6\times10^{16} entries, one per tour
  2. About 219⋅19≈1072^{19}\cdot19\approx10^7 entries and 2×1082\times10^8 steps
  3. About 202=40020^2=400 entries and 8000 steps
  4. About 220≈1062^{20}\approx10^6 entries and 10610^6 steps
Show the answer

B. About 219⋅19≈1072^{19}\cdot19\approx10^7 entries and 2×1082\times10^8 steps

SS ranges over the 2192^{19} subsets of the other 19 cities and jj over 19 cities; each entry is extended to at most 19 new cities, about 219⋅19⋅19≈1.9×1082^{19}\cdot19\cdot19\approx1.9\times10^8 steps. That is the point of the DP: (n−1)!/2(n-1)!/2 tours collapse into 2n−1(n−1)2^{n-1}(n-1) states.

Question 4

In a tree with nn vertices, ans[v]\mathrm{ans}[v] is the sum of the distances from vv to all vertices, and cc is a child of pp whose subtree has ss vertices. Which formula moves the answer from pp to cc?

  1. ans[c]=ans[p]+n−2s\mathrm{ans}[c]=\mathrm{ans}[p]+n-2s
  2. ans[c]=ans[p]−s\mathrm{ans}[c]=\mathrm{ans}[p]-s
  3. ans[c]=ans[p]+s\mathrm{ans}[c]=\mathrm{ans}[p]+s
  4. ans[c]=ans[p]+n−s\mathrm{ans}[c]=\mathrm{ans}[p]+n-s
Show the answer

A. ans[c]=ans[p]+n−2s\mathrm{ans}[c]=\mathrm{ans}[p]+n-2s

The ss vertices of cc's subtree get one step closer and the other n−sn-s one step farther: ans[p]−s+(n−s)\mathrm{ans}[p]-s+(n-s). Two passes, one for the sizes and ans[root]\mathrm{ans}[\text{root}] and one to push answers down, give every vertex's answer in O(n)O(n).

Question 5

An array of n=3000n=3000 numbers must be cut into contiguous pieces, from left to right; a piece costs (its maximum) ×\times (its length) plus a fixed fee. Minimize the total. Which DP fits?

  1. Interval DP dp[i][j]\mathrm{dp}[i][j] over a split point, O(n3)O(n^3)
  2. A prefix DP dp[j]=min⁡i(dp[i]+cost(i,j))\mathrm{dp}[j]=\min_i\big(\mathrm{dp}[i]+\mathrm{cost}(i,j)\big), O(n2)O(n^2) with a running maximum
  3. Bitmask DP over the set of cut positions
  4. Tree DP over a Cartesian tree of the array
Show the answer

B. A prefix DP dp[j]=min⁡i(dp[i]+cost(i,j))\mathrm{dp}[j]=\min_i\big(\mathrm{dp}[i]+\mathrm{cost}(i,j)\big), O(n2)O(n^2) with a running maximum

A piece's cost depends only on the piece, and the pieces are taken left to right, so the state is just "where the last piece ends". For each jj, scanning ii downward keeps the running maximum of the last piece: O(n2)≈9×106O(n^2)\approx9\times10^6 steps.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §14.2, "Matrix-chain multiplication".
  • A. Laaksonen, Competitive Programmer's Handbook (2018), chapter 10 (dynamic programming over subsets) and chapter 14 (tree algorithms) (free online).
  • J. Erickson, Algorithms (2019), chapter 3, "Dynamic Programming" (free online).
  • R. Bellman, "Dynamic programming treatment of the travelling salesman problem," Journal of the ACM 9(1) (1962), 61–63.