Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Speeding Up Dynamic Programming

Monotone queues, convex hulls and quadrangle inequalities.

Split 100,000 numbers into groups, where a group with sum SS costs S2+CS^2 + C. The dynamic program is one line: try every place where the last group could start. That is 5×1095 \times 10^9 transitions, far over any time limit. Read each candidate as a straight line, and the same program runs as 100,000 deque operations in milliseconds. Every speedup in this lesson works this way: the transition is a minimum over many earlier states, and structure in the cost lets you skip most of them.

What you’ll learn

  • Identify the minimum over earlier states as the bottleneck of a DP, and match the structure of its cost to a speedup: a monotone deque, the convex hull trick, divide-and-conquer optimization, Knuth's optimization or the Aliens trick.
  • Rewrite a transition as a minimum of lines and implement the monotone convex hull trick in O(n)O(n), with an overflow-safe intersection test.
  • State the quadrangle inequality, the monotone optimal split points it implies, and the before and after complexity of divide-and-conquer and Knuth's optimization.
  • Remove an "exactly kk groups" constraint with a penalty per group and a binary search, and say when this is exact.
  • Recognize which speedup a problem needs, and the look-alikes that need none.

Where the time goes

Many dynamic programs end in a minimum over earlier states:

dp[i]=min⁡0≤j<i(dp[j]+w(j,i)).dp[i] = \min_{0 \le j < i}\big(dp[j] + w(j, i)\big).

With nn states and up to nn candidates each, that costs Θ(n2)\Theta(n^2). Building kk layers dpkdp_k from dpk−1dp_{k-1} costs Θ(kn2)\Theta(kn^2), and an interval DP that tries every split point costs Θ(n3)\Theta(n^3). The speedups in this lesson keep the states and the values; they change only how the best jj is found, by exploiting structure in the cost ww.

The running example: split an array of positive numbers into consecutive groups, where a group with sum SS costs S2+CS^2 + C. The squares punish big groups and the constant CC punishes many groups. With prefix sums P[0]=0P[0] = 0, P[i+1]=P[i]+a[i]P[i+1] = P[i] + a[i], and the last group a[j..i−1]a[j..i-1] (inclusive):

dp[i]=min⁡0≤j<i(dp[j]+(P[i]−P[j])2+C),dp[0]=0dp[i] = \min_{0 \le j < i}\Big(dp[j] + \big(P[i] - P[j]\big)^2 + C\Big), \qquad dp[0] = 0
For a=3,1,4,1,5,9,2,6a = 3, 1, 4, 1, 5, 9, 2, 6 and C=30C = 30 the optimum is dp[8]=361dp[8] = 361: groups (3,1),(4,1),(5),(9),(2,6)(3, 1), (4, 1), (5), (9), (2, 6), costing 46+55+55+111+9446 + 55 + 55 + 111 + 94. With n=105n = 10^5 the direct double loop makes about 5×1095 \times 10^9 transitions.
TransitionStructure it needsTechniqueTime
dp[i]=c(i)+min⁡L(i)≤j<iv(j)dp[i] = c(i) + \min_{L(i) \le j < i} v(j)window ends that never move leftmonotone dequeO(nk)→O(n)O(nk) \to O(n)
dp[i]=min⁡j(mjxi+bj)+c(i)dp[i] = \min_j \big(m_j x_i + b_j\big) + c(i)slopes and queries both monotoneconvex hull trick with a dequeO(n2)→O(n)O(n^2) \to O(n)
the same, in any ordernone beyond the linesbinary search on the hull, or a Li Chao treeO(n2)→O(nlog⁡n)O(n^2) \to O(n \log n)
dpk[i]=min⁡j<i(dpk−1[j]+w(j,i))dp_k[i] = \min_{j < i}\big(dp_{k-1}[j] + w(j, i)\big)ww satisfies the quadrangle inequalitydivide-and-conquer optimizationO(kn2)→O(knlog⁡n)O(kn^2) \to O(kn \log n)
dp[i][j]=min⁡i<s<j(dp[i][s]+dp[s][j])+w(i,j)dp[i][j] = \min_{i < s < j}\big(dp[i][s] + dp[s][j]\big) + w(i, j)quadrangle inequality and monotone wwKnuth's optimizationO(n3)→O(n2)O(n^3) \to O(n^2)
exactly kk groupsoptimal cost convex in kkAliens trick: a penalty per groupO(kT)→O(Tlog⁡U)O(kT) \to O(T \log U)
The map of this lesson. TT is the time of one unconstrained DP and UU the range of the penalty searched.

The convex hull trick

Expand the square in the running example:

dp[i]=P[i]2+C+min⁡j<i(−2P[j]⏟mj⋅P[i]+dp[j]+P[j]2⏟bj).dp[i] = P[i]^2 + C + \min_{j < i}\big(\underbrace{-2P[j]}_{m_j} \cdot P[i] + \underbrace{dp[j] + P[j]^2}_{b_j}\big).

Each earlier state jj is a line y=mjx+bjy = m_j x + b_j, and dp[i]dp[i] needs the lowest line at x=P[i]x = P[i]. The lowest line at each xx traces the lower envelope, a concave piecewise-linear curve on which each line occupies at most one interval, in order of decreasing slope. The values are positive, so PP increases: lines arrive with decreasing slopes, and queries come with increasing xx.

DerivationThe pop test without division
  1. x12=b2−b1m1−m2,x13=b3−b1m1−m3x_{12} = \frac{b_2 - b_1}{m_1 - m_2}, \qquad x_{13} = \frac{b_3 - b_1}{m_1 - m_3}

    Two lines meet where max+ba=mbx+bbm_a x + b_a = m_b x + b_b:

  2. x13≤x12  ⟺  (b3−b1)(m1−m2)≤(b2−b1)(m1−m3)x_{13} \le x_{12} \iff (b_3 - b_1)(m_1 - m_2) \le (b_2 - b_1)(m_1 - m_3)

    Both denominators are positive because slopes decrease, so cross-multiplying keeps the inequality's direction:

  3. ∣(b3−b1)(m1−m2)∣≈1016⋅2×108≫263\abs{(b_3 - b_1)(m_1 - m_2)} \approx 10^{16} \cdot 2 \times 10^{8} \gg 2^{63}

    With n=105n = 10^5 values up to 10310^3, P[n]P[n] reaches 10810^8, intercepts reach about 101610^{16} and slope gaps 2×1082 \times 10^8, so the products approach 102410^{24}, far past 263≈9.2×10182^{63} \approx 9.2 \times 10^{18}. Multiply in 128 bits.

cpp
#include <cstdio>
#include <deque>
#include <vector>
using namespace std;
typedef long long ll;

struct Line {
    ll m, b;                                     // y = m*x + b
    ll at(ll x) const { return m * x + b; }
};

// With slopes m1 > m2 > m3, l2 is useless if l3 overtakes l1 no later than l2 does
bool useless(const Line& l1, const Line& l2, const Line& l3) {
    return (__int128)(l3.b - l1.b) * (l1.m - l2.m) <= (__int128)(l2.b - l1.b) * (l1.m - l3.m);
}

int main() {
    int n; ll C;                                 // n positive values; a group costs (sum)^2 + C
    scanf("%d %lld", &n, &C);
    vector<ll> P(n + 1, 0), dp(n + 1, 0);
    for (int i = 0; i < n; i++) { ll a; scanf("%lld", &a); P[i + 1] = P[i] + a; }
    deque<Line> hull = {{0, 0}};                 // the line of j = 0
    for (int i = 1; i <= n; i++) {
        ll x = P[i];                             // queries increase
        while (hull.size() >= 2 && hull[1].at(x) <= hull[0].at(x)) hull.pop_front();
        dp[i] = hull[0].at(x) + x * x + C;
        Line l = {-2 * P[i], dp[i] + P[i] * P[i]};   // slopes decrease
        while (hull.size() >= 2 && useless(hull[hull.size() - 2], hull.back(), l)) hull.pop_back();
        hull.push_back(l);
    }
    printf("%lld\n", dp[n]);
}

O(n)O(n) time. On input 8 30 and 3 1 4 1 5 9 2 6 it prints 361. __int128 is a GCC and Clang extension; elsewhere compare in long double and accept a small rounding risk. For maxima instead of minima, negate the lines.

Check your understanding

Which transition is a minimum of lines evaluated at a single query point, ready for the convex hull trick?

  1. dp[i]=min⁡j<i(dp[j]+max⁡(a[j+1..i]))dp[i] = \min_{j<i}\big(dp[j] + \max(a[j+1..i])\big)
  2. dp[i]=min⁡j<i(dp[j]+h[j+1]⋅w[i])dp[i] = \min_{j<i}\big(dp[j] + h[j+1] \cdot w[i]\big)
  3. dp[i]=min⁡j<i(dp[j]+(i−j)3)dp[i] = \min_{j<i}\big(dp[j] + (i - j)^3\big)
  4. dp[i]=min⁡j<i(dp[j]+gcd⁡(i,j))dp[i] = \min_{j<i}\big(dp[j] + \gcd(i, j)\big)
Show the answer

B. dp[i]=min⁡j<i(dp[j]+h[j+1]⋅w[i])dp[i] = \min_{j<i}\big(dp[j] + h[j+1] \cdot w[i]\big)

State jj contributes the line with slope h[j+1]h[j+1] and intercept dp[j]dp[j], evaluated at x=w[i]x = w[i]. The cost splits into a factor depending only on jj times a factor depending only on ii, plus terms in jj alone or ii alone.

Monotone split points: divide and conquer, and Knuth

Let opt(i)\text{opt}(i) be the smallest jj that achieves the minimum for state ii. In many DPs it never decreases: the best last group of a longer prefix starts no earlier. The classic sufficient condition is the quadrangle inequality on the cost,

w(a,c)+w(b,d)≤w(a,d)+w(b,c)for all a≤b≤c≤d:w(a, c) + w(b, d) \le w(a, d) + w(b, c) \qquad \text{for all } a \le b \le c \le d:

two overlapping intervals cost no more than the outer one plus the inner one. The running example satisfies it, because w(a,d)+w(b,c)−w(a,c)−w(b,d)=2(P[b]−P[a])(P[d]−P[c])≥0w(a, d) + w(b, c) - w(a, c) - w(b, d) = 2\big(P[b] - P[a]\big)\big(P[d] - P[c]\big) \ge 0 when PP increases.

Divide-and-conquer optimization builds layer dpkdp_k from dpk−1dp_{k-1}. Compute the middle state of a range by scanning all its candidates; then every state to its left needs only candidates up to opt(mid)\text{opt}(\text{mid}), and every state to its right only candidates from opt(mid)\text{opt}(\text{mid}) on. Each level of the recursion scans O(n)O(n) candidates in total, so a layer costs O(nlog⁡n)O(n \log n).

python
INF = float('inf')

def layer(prev, cost, n):                  # cur[i] = min over 0 <= j < i of prev[j] + cost(j, i)
    cur = [INF] * (n + 1)
    def solve(lo, hi, optlo, opthi):       # fill cur[lo..hi]; their best j lies in [optlo, opthi]
        if lo > hi:
            return
        mid = (lo + hi) // 2
        best, arg = INF, optlo
        for j in range(optlo, min(mid - 1, opthi) + 1):
            v = prev[j] + cost(j, mid)
            if v < best:                   # strict: keep the smallest best j
                best, arg = v, j
        cur[mid] = best
        solve(lo, mid - 1, optlo, arg)
        solve(mid + 1, hi, arg, opthi)
    solve(1, n, 0, n - 1)
    return cur

O(nlog⁡n)O(n \log n) evaluations of cost per layer and recursion depth O(log⁡n)O(\log n). Starting from prev = [0, inf, ..., inf] (zero groups cover only the empty prefix), kk calls give the best partition of a[0..n−1]a[0..n-1] into exactly kk groups in O(knlog⁡n)O(kn \log n).

Knuth's optimization handles interval DPs that try every split point, such as merging adjacent piles at a cost equal to the merged size, or building an optimal binary search tree. If ww satisfies the quadrangle inequality and is monotone under inclusion (w(b,c)≤w(a,d)w(b, c) \le w(a, d) whenever a≤b≤c≤da \le b \le c \le d), the largest optimal splits obey opt[i][j−1]≤opt[i][j]≤opt[i+1][j]\text{opt}[i][j-1] \le \text{opt}[i][j] \le \text{opt}[i+1][j], so each interval tries only the splits between its two neighbors' optima.

DerivationWhy Knuth’s windows add up to O(n²)
  1. ∑i=0n−ℓ(opt[i+1][i+ℓ]−opt[i][i+ℓ−1]+1)\sum_{i=0}^{n-\ell}\Big(\text{opt}[i+1][i+\ell] - \text{opt}[i][i+\ell-1] + 1\Big)

    The interval [i,i+ℓ)[i, i + \ell) tries opt[i+1][i+ℓ]−opt[i][i+ℓ−1]+1\text{opt}[i+1][i+\ell] - \text{opt}[i][i+\ell-1] + 1 splits. Sum along one diagonal of the table, all intervals of length ℓ\ell:

  2. =opt[n−ℓ+1][n]−opt[0][ℓ−1]+(n−ℓ+1)≤2n= \text{opt}[n-\ell+1][n] - \text{opt}[0][\ell-1] + (n - \ell + 1) \le 2n

    The first term for ii cancels the second term for i+1i + 1, so the sum telescopes:

  3. ∑ℓ=1nO(n)=O(n2)\sum_{\ell=1}^{n} O(n) = O(n^2)

    There are nn diagonals, so the whole table costs O(n2)O(n^2) instead of O(n3)O(n^3): a factor of nn saved, by amortization along each diagonal rather than per interval.

Check your understanding

Divide-and-conquer optimization relies on w(j,i)=(P[i]−P[j])2w(j, i) = \big(P[i] - P[j]\big)^2 satisfying the quadrangle inequality. When can that fail?

  1. When nn is not a power of two
  2. When the values are large
  3. When some values a[t]a[t] are negative, so that PP is not monotone
  4. Never: squared differences always satisfy it
Show the answer

C. When some values a[t]a[t] are negative, so that PP is not monotone

The gap w(a,d)+w(b,c)−w(a,c)−w(b,d)=2(P[b]−P[a])(P[d]−P[c])w(a, d) + w(b, c) - w(a, c) - w(b, d) = 2(P[b] - P[a])(P[d] - P[c]) is non-negative when PP never decreases. With negative values the two differences can have opposite signs, and the optimal split points need not be monotone. The convex hull trick still applies, because it uses only the algebraic form, but with slopes and queries out of order it needs a Li Chao tree.

Exactly k groups: the Aliens trick

Now demand exactly KK groups and drop the constant: let f(K)f(K) be the least total of squared group sums over partitions into KK consecutive groups. The layered DP costs O(Kn2)O(Kn^2), or O(Knlog⁡n)O(Kn \log n) with divide and conquer, too slow when KK is large as well. Instead, remove the constraint: charge a penalty λ\lambda per group and solve the unconstrained problem

g(λ)=min⁡partitions(cost+λ⋅#groups)=min⁡k(f(k)+λk).g(\lambda) = \min_{\text{partitions}}\big(\text{cost} + \lambda \cdot \#\text{groups}\big) = \min_{k}\big(f(k) + \lambda k\big).

That is the running example with C=λC = \lambda: O(n)O(n) with the convex hull trick. A larger penalty favors fewer groups, so binary search for a λ\lambda at which an optimum uses KK groups, and read off f(K)=g(λ)−λKf(K) = g(\lambda) - \lambda K. This is Lagrangian relaxation of the count constraint; contest programmers call it the Aliens trick, after a task at the 2016 International Olympiad in Informatics that made it popular.

DerivationWhen the penalty trick is exact
  1. g(λ)−λK≤f(K)g(\lambda) - \lambda K \le f(K)

    Always a lower bound. For every λ\lambda and KK, g(λ)≤f(K)+λKg(\lambda) \le f(K) + \lambda K, hence

  2. g(λ)=f(K)+λKg(\lambda) = f(K) + \lambda K

    Equality when KK is optimal for λ\lambda. If some optimal partition of the penalized problem has exactly KK groups, its cost is f(K)f(K) and

  3. f(K)−f(K+1)  ≤  λ  ≤  f(K−1)−f(K)  ⟹  f(K)+λK=min⁡k(f(k)+λk)f(K) - f(K+1) \;\le\; \lambda \;\le\; f(K-1) - f(K) \;\Longrightarrow\; f(K) + \lambda K = \min_k \big(f(k) + \lambda k\big)

    Convexity makes every KK optimal for some λ\lambda. If f(k−1)+f(k+1)≥2f(k)f(k-1) + f(k+1) \ge 2f(k) for all kk, the drops f(k−1)−f(k)f(k-1) - f(k) shrink as kk grows. For λ\lambda between the drops on either side of KK, adding a group beyond KK saves at most λ\lambda and removing one costs at least λ\lambda:

Which costs make ff convex? The quadrangle inequality again: the Optimal lesson Divide-and-Conquer Optimization & the Aliens Trick proves that it implies f(k−1)+f(k+1)≥2f(k)f(k-1) + f(k+1) \ge 2f(k), by exchanging the tails of two partitions. The total cost is O(Tlog⁡U)O(T \log U), where TT is the time of one penalized DP and UU the range of λ\lambda; here U≤P[n]2U \le P[n]^2, about 54 halvings for P[n]=108P[n] = 10^8.

Recognizing it

Signals in a problem statement and its constraints:

  • an obvious O(n2)O(n^2), O(kn2)O(kn^2) or O(n3)O(n^3) DP with nn around 10510^5 (or 50005000 for O(n3)O(n^3)), well past the rule of thumb of about 10810^8 simple operations per second;
  • a cost of the form (term in j)×(term in i)\text{(term in } j) \times \text{(term in } i) plus separate terms, often from expanding a square: lines, so the convex hull trick;
  • "split into consecutive groups" with a cost that grows faster than linearly with the group (squares of sums, distances to a center): the quadrangle inequality, so divide and conquer or Knuth;
  • "exactly kk groups" with kk up to nn: the Aliens trick, if the cost is convex in kk;
  • a window constraint such as "at most kk steps back": the monotone deque.
Problem (in brief)TransitionSpeedupCost
A frog jumps at most kk stones ahead; minimize the landing costsdp[i]=ci+min⁡i−k≤j<idp[j]dp[i] = c_i + \min_{i-k \le j < i} dp[j]monotone dequeO(n)O(n)
Split an array into groups costing (sum)2+C(\text{sum})^2 + Clines −2P[j] x+dp[j]+P[j]2-2P[j]\,x + dp[j] + P[j]^2 at x=P[i]x = P[i]convex hull trickO(n)O(n)
Buy rectangular plots in groups costing (widest) × (tallest)after sorting and pruning: dp[j]+hj+1widp[j] + h_{j+1} w_iconvex hull trickO(nlog⁡n)O(n \log n), for the sort
Merge adjacent piles into one, paying each merged pile's sizeinterval DP over split pointsKnuth's optimizationO(n2)O(n^2)
Place kk post offices among nn houses on a linelayered DP; a group costs its distances to its mediandivide and conquer, or the Aliens trickO(knlog⁡n)O(kn \log n), or O(nlog⁡nlog⁡U)O(n \log n \log U)
A look-alike that needs none of this: minimize the largest group sum with at most kk groups. It is a partition DP too, but a bottleneck objective has a monotone yes/no check ("can every group stay at most ss?", answered greedily), so binary search on the answer solves it in O(nlog⁡S)O(n \log S) for total SS, as in the widget below.

Key takeaways

  • Most slow DPs spend their time in a minimum over earlier states; the speedups keep the states and find the best candidate faster by exploiting structure in the cost.
  • If the cost factors as (term in jj) × (term in ii) plus separate terms, each candidate is a line and the minimum is a lower envelope: O(n)O(n) with a deque when slopes and queries are monotone, O(nlog⁡n)O(n \log n) otherwise.
  • The quadrangle inequality makes optimal split points monotone: divide and conquer computes a layer in O(nlog⁡n)O(n \log n), and Knuth's windows make interval DP O(n2)O(n^2) by telescoping.
  • "Exactly kk" constraints with a cost convex in kk become a penalty λ\lambda per group, a binary search on λ\lambda, and the answer g(λ)−λKg(\lambda) - \lambda K, with consistent tie-breaking.
  • Stress test every speedup against the plain DP: a violated condition does not crash, it gives wrong answers.

Check yourself

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

Question 1

In the monotone convex hull trick, a query at xx pops the front line once the second line is no higher at xx. Why may that line be discarded for good?

  1. Because every line is used by exactly one query
  2. Because the front line has the larger slope, two lines cross at most once, and later queries have larger xx, so the second line stays at least as low
  3. Because the deque is sorted by intercept
  4. It may not: a later query can need it again, so it must be re-inserted
Show the answer

B. Because the front line has the larger slope, two lines cross at most once, and later queries have larger xx, so the second line stays at least as low

For m1>m2m_1 > m_2, the difference (m1−m2)x+(b1−b2)(m_1 - m_2)x + (b_1 - b_2) increases with xx, so once the second line is no higher, it stays no higher for every larger xx. That is why the queries must be monotone; for queries in any order, binary search over the hull instead of popping.

Question 2

With Knuth's optimization, interval [i,j)[i, j) tries only the splits from opt[i][j−1]\text{opt}[i][j-1] to opt[i+1][j]\text{opt}[i+1][j]. What is the total running time for nn piles?

  1. O(n3)O(n^3), since one interval can still try Θ(n)\Theta(n) splits
  2. O(n2log⁡n)O(n^2 \log n)
  3. O(n2)O(n^2)
  4. O(nlog⁡n)O(n \log n)
Show the answer

C. O(n2)O(n^2)

One interval may still try many splits, but along each diagonal the windows telescope to at most 2n2n splits in total, and there are nn diagonals.

Question 3

The penalized DP with λ=7\lambda = 7 per group has optimal value g(7)=250g(7) = 250, and with consistent tie-breaking the binary search shows that λ=7\lambda = 7 is right for K=4K = 4 groups. What is the least cost f(4)f(4) with exactly 4 groups?

  1. 250
  2. 278
  3. 222
  4. 250/4=62.5250/4 = 62.5
Show the answer

C. 222

g(λ)g(\lambda) includes the penalty for the KK groups, so f(K)=g(λ)−λK=250−7⋅4=222f(K) = g(\lambda) - \lambda K = 250 - 7 \cdot 4 = 222.

Question 4

Which problem is best solved by binary search on the answer rather than by a DP speedup?

  1. Split an array into kk consecutive groups minimizing the sum of squared group sums
  2. Split an array into kk consecutive groups minimizing the largest group sum
  3. Merge adjacent piles into one at minimum total cost
  4. Place kk post offices among houses on a line, minimizing the total distance
Show the answer

B. Split an array into kk consecutive groups minimizing the largest group sum

For a bottleneck objective, "can every group stay at most ss?" is answered by a greedy scan and is monotone in ss, so binary search over ss finds the optimum in O(nlog⁡S)O(n \log S). The others add up costs over the groups and need the DP, sped up by divide and conquer or the Aliens trick, Knuth, and divide and conquer respectively.

Go deeper

Further reading

  • D. E. Knuth, "Optimum binary search trees," Acta Informatica 1 (1971).
  • F. F. Yao, "Efficient dynamic programming using quadrangle inequalities," Proceedings of the 12th ACM Symposium on Theory of Computing (1980).
  • CP-Algorithms: "Convex hull trick and Li Chao tree", "Divide and Conquer DP" and "Knuth's Optimization".
  • A. Aggarwal, B. Schieber & T. Tokuyama, "Finding a minimum-weight k-link path in graphs with the concave Monge property and applications," Discrete & Computational Geometry 12 (1994).