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.

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

School of Engineering, Nazarbayev University

Worked solutions to the three exercises of Lecture 6. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.

Exercise 1

Problem. 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).


Exercise 1: Metric-space axioms of edit distance and Needleman-Wunsch score duality
===================================================================================
Verified all 4 metric axioms on 10x10 pairwise matrix and 1000 ordered triples
Minimum triangle slack min(d(x,y) + d(y,z) - d(x,z)) = 0 (tight equality achieved)
<Figure size 748x473 with 2 Axes>

Figure S6.1. Edit distances between the ten sequences of the corpus. The matrix is symmetric with a zero diagonal.

Explanation. Every valid edit script transforming x→yx \to y (d(x,y)d(x,y) operations) followed by an edit script transforming y→zy \to z (d(y,z)d(y,z) operations) composes into a valid transformation x→zx \to z of length d(x,y)+d(y,z)d(x,y) + d(y,z); since d(x,z)d(x,z) is the minimum over all valid scripts x→zx \to z, d(x,z)≤d(x,y)+d(y,z)d(x,z) \leq d(x,y) + d(y,z) holds universally whenever single-character insertion and deletion costs are equal (guaranteeing symmetry as well).


Exercise 2

Problem. 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.


Exercise 2: Failure-mode audit — forward-sweep knapsack cloning and greedy seam trapping
========================================================================================
Knapsack 1-D audit : True 0/1 = 34.0 (backward = 34.0) vs. Forward-sweep bug = 48.0 (cloned item 3x)
Seam Carving audit : Global DP energy = 4.80 vs. Greedy top-down trap = 260.55 (54.3x worse)

Explanation. (a) In 1-D Knapsack, dp[c - w_i] must hold V(i−1,c−wi)V(i-1, c - w_i) from the previous item row. Sweeping c upward overwrites dp[3] = 16, then uses that updated dp[3] at c = 6 (dp[6] = 32) and c = 9 (dp[9] = 48), turning 0/1 into Unbounded Knapsack. (b) Because an 8-connected seam can drift laterally by at most ±1\pm 1 column per row, entering the left bait at (0, 2) leaves the greedy walker trapped inside columns 0..5 when row 7’s 250.0 barrier arrives—whereas global DP integrates future row costs before committing at row 0.


Exercise 3

Problem. 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.


Exercise 3: Implement it yourself — iterative multi-seam scientific field retargeting
=====================================================================================
Original shape (36, 64) -> Carved shape (36, 48)
Left/Right plume peaks : Original (1.982, 1.773) -> Carved (1.982, 1.773)
Plume core mass loss   : Seam Carving = 0.000% vs. Naive Border Crop = 38.8%
<Figure size 990x418 with 2 Axes>

Figure S6.2. Seam carving of a synthetic two-plume field. (a) The original 36 × 64 field. (b) The field after removing 16 seams, 36 × 48, with both plumes intact.

Summary. Recomputing the gradient energy field after each vertical seam removal prevents multiple seams from collapsing onto neighboring high-gradient shoulders, so the 16 seams remove 25 % of the width from the calm background: the plume core loses 0.000 % of its mass, against 38.8 % for cropping the right-hand border.