Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

6. Dynamic programming: knapsack, sequence alignment and seam carving

School of Engineering, Nazarbayev University

A naive recursive function that aligns two 14-character telemetry strings makes about 1010 calls, while a dynamic programming (DP) table of 225 cells gives the same answer. The idea behind the table is Mental Move #15, Tabulate Overlapping Subproblems Once: whenever exponential recursion repeatedly revisits the same small set of states, collapsing that call tree into a Directed Acyclic Graph (DAG) turns O(2N)\mathcal{O}(2^N) or O(3N)\mathcal{O}(3^N) brute force into polynomial shortest- or longest-path relaxation. In this lecture, you will see how one algorithmic blueprint—topological relaxation on an implicit state DAG with backpointers—unifies discrete 0/1 sensor-payload allocation (dynamic_optimality.knapsack_01_dp), noisy Needleman–Wunsch sequence alignment & Levenshtein edit distance (dynamic_optimality.sequence_alignment_dp, edit_distance_dp), and Avidan & Shamir’s (2007) 2-D content-aware seam carving (dynamic_optimality.seam_carving_min_energy).

Learning objectives

  1. Quantify why naive divide-and-conquer grows exponentially when subproblems overlap, and collapse exponential call trees into polynomial DAG state tables via memoization and bottom-up tabulation.

  2. Formulate exact 0/1 integer-capacity resource allocation (dynamic_optimality.knapsack_01_dp) and bracket its optimal value between greedy value-density heuristics and Dantzig’s fractional LP relaxation.

  3. Cast Needleman–Wunsch global sequence alignment (dynamic_optimality.sequence_alignment_dp) and Wagner–Fischer edit distance (dynamic_optimality.edit_distance_dp) as longest/shortest paths on an (M+1)×(N+1)(M+1)\times(N+1) edit DAG.

  4. Compute minimum-energy 8-connected vertical seams (dynamic_optimality.seam_carving_min_energy) to resize 2-D scientific fields without distorting high-gradient features, and compress DP memory via rolling two-row buffers.

Time: about 60 min

1. Overlapping Subproblems: Exponential Call Trees vs. Polynomial State DAGs

Divide-and-conquer works well when subproblems are disjoint (like MergeSort splitting an array into two non-overlapping halves). When subproblems overlap, naive recursion recomputes the same states a very large number of times.

Consider aligning two prefixes of lengths (i,j)(i, j) where each state (i,j)(i, j) branches into three predecessors: (i−1,j)(i-1, j) (deletion), (i,j−1)(i, j-1) (insertion), and (i−1,j−1)(i-1, j-1) (match/substitution). Without memoization, the total number of recursive invocations C(m,n)C(m, n) obeys:

C(m,n)=1+C(m−1,n)+C(m,n−1)+C(m−1,n−1),C(i,0)=C(0,j)=1(1.1)C(m, n) = 1 + C(m-1, n) + C(m, n-1) + C(m-1, n-1), \qquad C(i, 0) = C(0, j) = 1 \tag{1.1}

Along the diagonal m=nm = n, C(n,n)C(n, n) grows faster than the central Delannoy numbers D(n,n)∼(1+2)2n+12πn≈5.828nnD(n, n) \sim \frac{(1 + \sqrt{2})^{2n+1}}{2\sqrt{\pi n}} \approx \frac{5.828^n}{\sqrt{n}}. Yet how many distinct argument pairs (i,j)(i, j) can ever exist in 0≤i≤m,  0≤j≤n0 \leq i \leq m,\; 0 \leq j \leq n? Exactly (m+1)(n+1)(m + 1)(n + 1).

Naive Tree Calls Θ ⁣((3+22)NN−1/2)→DAG TabulationUnique States (N+1)2=Θ(N2)(1.2)\text{Naive Tree Calls } \Theta\!\left((3 + 2\sqrt{2})^N N^{-1/2}\right) \quad \xrightarrow{\text{DAG Tabulation}} \quad \text{Unique States } (N + 1)^2 = \Theta(N^2) \tag{1.2}

Every dynamic program requires just two structural ingredients:

  1. Optimal Substructure: An optimal path to state uu extends an optimal path to one of its incoming DAG predecessors p∈Pred(u)p \in \mathrm{Pred}(u).

  2. Overlapping Subproblems: Many exponentially numerous paths funnel through the same polynomial vertex set VDAGV_{\mathrm{DAG}}.


Demonstration 1: Exponential call trees against polynomial DAG tabulation
=========================================================================
Mental Move #15 (Tabulate Overlapping Subproblems Once): Each state is solved once, in topological order of the DAG
Length N |  Naive Tree Calls C(N,N) |  DAG States (N+1)^2 |   Redundancy Ratio
------------------------------------------------------------------------------
       2 |                       19 |                   9 |               2.1x
       4 |                      481 |                  25 |              19.2x
       6 |                   13,483 |                  49 |             275.2x
       8 |                  398,593 |                  81 |            4920.9x
      10 |               12,146,179 |                 121 |          100381.6x
      12 |              377,393,953 |                 169 |         2233100.3x
      14 |           11,885,772,379 |                 225 |        52825655.0x
<Figure size 814x451 with 1 Axes>

Figure 6.1. Calls of the naive three-way alignment recursion, C(N,N)C(N, N), against the number of distinct states (N+1)2(N+1)^2 that a table has to fill. At N=14N = 14 the ratio is 5.3×1075.3 \times 10^7.

What Demonstration 1 shows. At length N=14N = 14, the naive three-way recursion makes 1.19×10101.19 \times 10^{10} calls, whereas tabulation fills 15×15=22515 \times 15 = 225 cells, a ratio of 5.3×1075.3 \times 10^7, obtained only by never solving a state (i,j)(i, j) twice.


2. Discrete 0/1 Knapsack Allocation vs. Greedy & Fractional Relaxation

Suppose an autonomous underwater vehicle (AUV) has an integer payload mass budget W∈Z≥0W \in \mathbb{Z}_{\geq 0} [kg] and NN candidate scientific instruments with integer masses wi>0w_i > 0 and information values vi>0v_i > 0. Each instrument is indivisible (xi∈{0,1}x_i \in \{0, 1\}): you cannot saw a mass spectrometer in half.

Let V(i,c)V(i, c) denote the maximum value achievable using a subset of the first ii instruments within capacity c∈{0,1,…,W}c \in \{0, 1, \dots, W\}. Conditioning on whether instrument ii is excluded (xi=0x_i = 0) or included (xi=1x_i = 1) yields Bellman’s recurrence:

V(i,c)=max⁡ ⁣(V(i−1,c),  I[wi≤c]⋅(V(i−1,c−wi)+vi)),V(0,c)=0(2.1)V(i, c) = \max\!\Big(V(i - 1, c),\; \mathbb{I}[w_i \leq c]\cdot \big(V(i - 1, c - w_i) + v_i\big)\Big), \qquad V(0, c) = 0 \tag{2.1}

How does exact 0/1 DP compare against two fast approximations?

  • Greedy Value-Density Heuristic: Sort items by vi/wiv_i / w_i descending and pack whole items that fit. Fast (O(Nlog⁡N)\mathcal{O}(N \log N)), but a single bulky high-ratio item can strand unused capacity (packing fragmentation).

  • Dantzig’s Fractional Relaxation (xi∈[0,1]x_i \in [0, 1]): Take highest vi/wiv_i / w_i items plus a fractional slice of the boundary item to fill WW completely. Because {0,1}N⊂[0,1]N\{0, 1\}^N \subset [0, 1]^N, this gives a provable LP upper bound:

Vgreedy(W)  ≤  V0/1∗(W)  ≤  Vfractional(W)(2.2)V_{\mathrm{greedy}}(W) \;\leq\; V_{0/1}^*(W) \;\leq\; V_{\mathrm{fractional}}(W) \tag{2.2}

Demonstration 2: 0/1 payload knapsack DP against greedy density and fractional LP bound
=======================================================================================
Capacity W = 10 kg:
  Greedy (by v/w)  :  46.5 pts -> ['Multibeam', 'MagArray'] (mass = 9 kg)
  Exact 0/1 DP     :  52.5 pts -> ['CTD-Pro', 'MassSpec'] (mass = 10 kg)
  Fractional LP UB :  54.2 pts (integrality gap = 1.70 pts)
<Figure size 825x462 with 1 Axes>

Figure 6.2. Value of the instrument payload against the mass budget WW for the seven instruments of Demonstration 2. The exact 0/1 dynamic program (solid) lies between the greedy density rule (dotted) and the fractional upper bound (dashed); at W=10 kgW = 10\,\mathrm{kg} (vertical line) the values are 46.5, 52.5 and 54.2.

What Demonstration 2 shows. At W=10 kgW = 10\ \mathrm{kg}, Multibeam (w=6 kg,v=33w=6\ \mathrm{kg}, v=33, density 5.50 pts/kg5.50\ \mathrm{pts/kg}) is taken first by the greedy heuristic. That leaves 4 kg4\ \mathrm{kg}, of which MagArray (3 kg3\ \mathrm{kg}, v=13.5v = 13.5) fits, for 46.5 pts46.5\ \mathrm{pts} with 1 kg1\ \mathrm{kg} unused, whereas knapsack_01_dp pairs CTD-Pro and MassSpec (5+5=10 kg5 + 5 = 10\ \mathrm{kg}) for the optimum, 52.5 pts52.5\ \mathrm{pts}. The fractional bound is 54.2 pts54.2\ \mathrm{pts}. Note also that knapsack_01_dp runs in O(NW)\mathcal{O}(N W) pseudo-polynomial time: polynomial in the numeric capacity WW, which is fast whenever WW is moderate.


3. Sequence Alignment & Edit Distance as Optimal Paths on a 2-D Grid DAG

From noisy deep-space telemetry packets to CRISPR off-target DNA screening, comparing two variable-length strings A=a1…aMA = a_1 \dots a_M and B=b1…bNB = b_1 \dots b_N means finding the highest-scoring alignment (or fewest single-character edits) transforming AA into BB.

Needleman & Wunsch (1970) cast global alignment as a longest-path problem on an (M+1)×(N+1)(M+1)\times(N+1) grid DAG with match reward smatchs_{\mathrm{match}}, mismatch penalty smiss_{\mathrm{mis}}, and linear gap penalty sgaps_{\mathrm{gap}}:

F(i,j)=max⁡ ⁣{F(i−1,j−1)+σ(ai,bj)(diagonal: align ai↔bj),F(i−1,j)+sgap(vertical: delete ai↔’-’),F(i,j−1)+sgap(horizontal: insert ’-’ ↔bj),(3.1)F(i, j) = \max\!\begin{cases} F(i-1, j-1) + \sigma(a_i, b_j) & \text{(diagonal: align } a_i \leftrightarrow b_j\text{)}, \\[3pt] F(i-1, j) + s_{\mathrm{gap}} & \text{(vertical: delete } a_i \leftrightarrow \text{'-'}\text{)}, \\[3pt] F(i, j-1) + s_{\mathrm{gap}} & \text{(horizontal: insert '-' } \leftrightarrow b_j\text{)}, \end{cases} \tag{3.1}

with boundary conditions F(i,0)=i sgapF(i, 0) = i\,s_{\mathrm{gap}} and F(0,j)=j sgapF(0, j) = j\,s_{\mathrm{gap}}. Setting (smatch,smis,sgap)=(0,−1,−1)(s_{\mathrm{match}}, s_{\mathrm{mis}}, s_{\mathrm{gap}}) = (0, -1, -1) turns maximization into minimization of Wagner–Fischer / Levenshtein edit distance: dedit(A,B)=−F(M,N)d_{\mathrm{edit}}(A, B) = -F(M, N).


Demonstration 3: Needleman-Wunsch alignment and edit-distance traceback
=======================================================================
Transmitted : SYNC_HDR_A47F_-CRC
              ||| |||| ||.|| |||
Received    : SYN-_HDR-A49F_GCRC
NW Score    : 21.0 (14 matches, 1 mismatches, 3 gaps) | Levenshtein Edit Distance = 4
<Figure size 814x495 with 2 Axes>

Figure 6.3. Needleman–Wunsch score table F(i,j)F(i, j) for the transmitted and received packet headers, with the optimal traceback path. Horizontal and vertical steps are gaps, diagonal steps matches or substitutions.

What Demonstration 3 shows. Without alignment, comparing seq_tx and seq_rx character-by-character at fixed index kk makes almost every character after index 3 look corrupted because a single dropped 'C' shifted the entire frame. Dynamic programming separates phase/timing slips (insertions & deletions, horizontal/vertical DAG edges) from symbol noise (substitutions, diagonal edges).


4. Content-Aware 2-D Seam Carving Around High-Gradient Scientific Features

Suppose you want to narrow an H×WH \times W 2-D physical scalar field ϕ(r,c)\phi(r, c) (such as vorticity, temperature, or astronomical intensity) without cropping away boundary structures or squishing localized peaks via uniform interpolation. Avidan & Shamir (ACM SIGGRAPH, 2007) defined an 8-connected vertical seam as one pixel per row (r,cr)r=0H−1(r, c_r)_{r=0}^{H-1} obeying ∣cr−cr−1∣≤1|c_r - c_{r-1}| \leq 1, minimizing cumulative gradient energy E(r,c)=∣∂xϕ∣+∣∂yϕ∣E(r, c) = |\partial_x \phi| + |\partial_y \phi|:

M(r,c)=E(r,c)+min⁡c′∈{c−1, c, c+1}∩[0,W−1]M(r−1,c′),M(0,c)=E(0,c)(4.1)M(r, c) = E(r, c) + \min_{c' \in \{c-1,\, c,\, c+1\} \cap [0, W-1]} M(r - 1, c'), \qquad M(0, c) = E(0, c) \tag{4.1}

Look at Equation (4.1): it is shortest-path relaxation on a layered row-by-row DAG in strictly O(HW)\mathcal{O}(HW) operations (3HW3HW comparisons). We compute the minimum-energy seam for a field with three localized vortex peaks and then several further seams, each penalised where an earlier one ran.


Demonstration 4: Avidan-Shamir seam carving around localized vortex cores
=========================================================================
Optimal 8-connected DP seam energy : 0.0088
Best straight vertical column      : 0.0088
Mean column gradient energy        : 1.8162 (206.6x higher than DP seam)
<Figure size 1034x440 with 4 Axes>

Figure 6.4. Seam carving of a synthetic field with three vortex cores. (a) The field and eight successive minimum-energy seams, each penalised once used; most follow the calm columns at the edges. (b) The cumulative energy table M(r,c)M(r, c) of the first seam, which runs down the right-hand edge.

What Demonstration 4 shows.

  • The best seam has energy 0.0088, the same as the best straight column: calm columns near the edges of this field already avoid all three vortices, and the dynamic program finds one of them. The mean column energy is 207 times higher. Seams that must pass between the vortices appear in the figure once the calm columns are penalised.


Inside the algorithm

The three dynamic programs share one practical point:

  • When we need full path reconstruction (which items were packed, which characters aligned, which column c∗(r)c^*(r) was carved), we store the O(MW)\mathcal{O}(MW) or O(MN)\mathcal{O}(MN) table (or Hirschberg divide-and-conquer split points).

  • When we only need the optimal scalar cost (such as Levenshtein edit distance dedit(A,B)d_{\mathrm{edit}}(A, B) across two 50,00050{,}000-base sequences, where a full 50,000250{,}000^2 float64 table would demand 20 GB20\ \mathrm{GB} of RAM), row ii depends only on row i−1i - 1. By swapping strings so ∣B∣≤∣A∣|B| \leq |A| and maintaining two rolling 1-D rows, memory collapses from O(MN)\mathcal{O}(MN) to O(min⁡(M,N))\mathcal{O}(\min(M, N)).

We inspect seam_carving_min_energy and knapsack_01_dp, then implement and verify space_compressed_edit_distance_2row from scratch.

Check against the library


Inside the algorithm: Seam carving, 0/1 knapsack and 2-row space-compressed DP
==============================================================================
def seam_carving_min_energy(energy_map: np.ndarray) -> dict:
    """Find the minimum-energy 8-connected top-to-bottom vertical seam in a 2-D field via Avidan-Shamir DP."""
    e_map = np.asarray(energy_map, dtype=float)
    if e_map.ndim != 2 or e_map.shape[0] < 2 or e_map.shape[1] < 2 or np.any(e_map < 0.0):
        raise ValueError("Require non-negative 2-D energy_map with shape >= (2, 2).")
    h, w = e_map.shape
    cum = np.zeros_like(e_map)
    back = np.zeros((h, w), dtype=int)
    cum[0, :] = e_map[0, :]

    for r in range(1, h):
        prev = cum[r - 1, :]
        for c in range(w):
            c_lo = max(0, c - 1)
            c_hi = min(w - 1, c + 1)
            best_prev_c = c_lo + int(np.argmin(prev[c_lo : c_hi + 1]))
            back[r, c] = best_prev_c
            cum[r, c] = e_map[r, c] + prev[best_prev_c]

    seam = np.zeros(h, dtype=int)
    seam[-1] = int(np.argmin(cum[-1, :]))
    min_e = float(cum[-1, seam[-1]])
    for r in range(h - 1, 0, -1):
        seam[r - 1] = back[r, seam[r]]

    return {"seam_cols": seam, "min_total_energy": min_e, "cumulative_energy_map": cum}

def knapsack_01_dp(weights: np.ndarray, values: np.ndarray, capacity: int) -> dict:
    """Solve exact 0/1 integer-capacity knapsack via dynamic programming with subset backpointer reconstruction."""
    w = np.asarray(weights, dtype=int).ravel()
    v = np.asarray(values, dtype=float).ravel()
    cap = int(capacity)
    if w.size != v.size or cap < 0 or np.any(w <= 0):
        raise ValueError("Require matching positive integer weights, values, and capacity >= 0.")

    n = w.size
    dp = np.zeros((n + 1, cap + 1), dtype=float)
    for i in range(1, n + 1):
        wi = int(w[i - 1])
        vi = float(v[i - 1])
        dp[i, :] = dp[i - 1, :]
        if wi <= cap:
            cand = dp[i - 1, : cap + 1 - wi] + vi
            dp[i, wi:] = np.maximum(dp[i, wi:], cand)

    chosen: list[int] = []
    rem = cap
    for i in range(n, 0, -1):
        if dp[i, rem] > dp[i - 1, rem] + 1e-12:
            chosen.append(i - 1)
            rem -= int(w[i - 1])
    chosen.reverse()
    return {
        "max_value": float(dp[n, cap]),
        "selected_indices": chosen,
        "total_weight": int(sum(w[idx] for idx in chosen)),
        "dp_states_evaluated": n * (cap + 1),
    }

Verified 2-row edit distance across 7 benchmark pairs with 0 discrepancies
Pair #7 memory footprint: full table = 2350 ints vs. 2-row buffer = 94 ints (25.0x smaller)

Exercises

Worked solutions are in 06_solutions.ipynb. The cell below the list is a short self-check to start from.

  1. Verify a result. Verify across a 10-sequence noisy DNA/telemetry corpus that dynamic_optimality.edit_distance_dp obeys the metric axioms (non-negativity, identity d(x,y)=0  ⟺  x=yd(x,y)=0 \iff x=y, symmetry d(x,y)=d(y,x)d(x,y)=d(y,x), and the triangle inequality d(x,z)≤d(x,y)+d(y,z)d(x,z) \leq d(x,y) + d(y,z) across all 1,0001{,}000 ordered triples—and confirm exact Needleman–Wunsch scaling FNW(x,y;0,−α,−α)=−α dedit(x,y)F_{\mathrm{NW}}(x, y; 0, -\alpha, -\alpha) = -\alpha\,d_{\mathrm{edit}}(x, y).

  2. Find how it fails. Verify all ValueError input guards on knapsack_01_dp and seam_carving_min_energy, then demonstrate quantitatively (a) why sweeping capacity forward in 1-D Knapsack DP corrupts 0/1 uniqueness into Unbounded Knapsack item cloning, and (b) why greedy local top-to-bottom seam stepping gets trapped by downstream barriers that global DP easily routes around.

  3. Implement it yourself. Implement remove_k_vertical_seams(image_2d, k_seams) using centered finite-difference gradient energy E=∣∂xϕ∣+∣∂yϕ∣E = |\partial_x \phi| + |\partial_y \phi| and dynamic_optimality.seam_carving_min_energy at each step. On a 36×6436 \times 64 two-plume scalar field with k_seams = 16, verify exact output shape (36, 48), exact preservation of both plume maxima, and >5×>5\times better preservation of high-intensity plume mass than right-side cropping.


Self-check for the exercises
============================
All checks passed.