Learning pathsPricingChecking sign-in…
Trees, graphs and optimization

Dynamic programming

Reuse solutions to repeated subproblems.

DP reuses answers to repeated subproblems, but only after their meaning and dependency order are clear.

Mechanism and state

For minimum coin count, dp[value] means the fewest coins making exactly value, or unreachable. dp[0]=0; other states start at amount+1. Try each positive last coin c using 1+dp[value-c], and evaluate amounts upward because every dependency is smaller. Unlimited reuse follows from reading the same table’s smaller amounts. A flight-stop limit adds a resource dimension. Let D_r(v) be the cheapest cost reaching vertex v with at most r flights. Clone D_(r−1) to preserve shorter routes, then relax every flight using only that frozen old layer. Two rolling arrays retain only the live dependency frontier. DSA-126–129 make the same discipline concrete on one-dimensional prefixes: W(s) counts ordered stair paths, D(t) minimizes cost to arrive before paying to depart, and B(k) maximizes a nonadjacent selection among the first k houses. The aggregate changes from sum to min to max, but each recurrence must keep its own state meaning and base. Only after the full recurrence is justified do two old scalar states replace a complete table. Compute next before shifting either old register. DSA-131 fixes a denomination-type layer before scanning sums upward, which counts unordered multisets with exact BigInteger addition. DSA-132 treats text boundaries as a word-edge DAG and expands a trie only from reachable starts. DSA-133 compresses equal-length subsequences by minimum-tail dominance rather than by nearby array position. DSA-134/135 use two-prefix grids; in one score row, old up and diagonal coexist with new left, so save the old up before overwriting it. DSA-136/137 use the same right/down grid DAG with different aggregates: exact path counts add disjoint final-move families, while minimum cost chooses a predecessor and adds the current charge. DSA-138 reads an old occurrence layer by scanning amounts downward. DSA-139 gates two prefix-count contributions by valid decimal token widths. DSA-140 retains both minimum and maximum products ending at the current index, since negative multiplication reverses order. Counting Bits tabulates popcount(i)=popcount(i>>>1)+(i&1), with the required output array also holding smaller finalized parents. Power x to n uses exponent parity and repeated squaring with no memo table: its dependency chain shrinks by halving rather than requiring overlapping-subproblem storage.

Why the pattern works

Any solution has a last coin and a suffix subproblem. An optimal full solution must use an optimal reachable suffix, otherwise replacing it improves the whole. Conversely each reachable candidate constructs a valid solution. This proves the recurrence by induction, including unreachable states. A permitted route either already uses at most r−1 flights or ends with an edge whose prefix uses at most r−1. These exhaustive cases give D_r(v)=min(D_(r−1)(v), min_u(D_(r−1)(u)+w(u,v))). Reading next within a round would violate the induction by consuming extra edges. A last-move partition counts stair paths in disjoint families. Minimum stair cost charges the predecessor, since the destination is not yet departed. Linear robbery partitions feasible subsets into taking the current house and skipping it; taking reads the two-back optimum. For a circle, every feasible subset excludes the first or the last house, so the maximum of the two path optima is exact. Those cases overlap; maximum tolerates overlap, while counting would double-count it. Coin-count layers split into zero-copy and at-least-one-copy families; reversing their loop nesting changes the counted objects. Word-boundary reachability merges histories only because words remain reusable. A smaller LIS endpoint dominates a larger one of the same length, but tails for different lengths need not coexist as a witness. LCS maximizes matched alignment length, while edit distance minimizes unit-cost alignment operations; both have complete final-column cases and different empty-prefix boundaries. A partition target is half the validated total, and its complement proves sufficiency. Descending sums enforce one use of each physical occurrence, including duplicates. Decode-token families are disjoint by their final width; zero is never a standalone token. Maximum-product intervals either restart at the current singleton or extend an immediately preceding interval; multiplication sends one of the old extremes to each new extreme. For i=2q+b, removing the final bit leaves q<i and adds exactly b one bits, so increasing numeric order is a valid tabulation order. Exponentiation uses the ideal identity r*f^(2q+b)=(r*f^b)*(f*f)^q, while its double contract separately defines rounded execution.

Work through an example

For coins [1,3,4], amount 6, the best counts for 0..6 are [0,1,2,1,1,2,2]. Largest-first greedy uses 4+1+1, but DP finds 3+3. For coins [2], amount 3 remains unreachable. In DSA-114, flights 0→1 and 1→2 cost one each while 0→2 costs eight. With zero intermediate stops only one edge is allowed, so the answer is eight; the newly written next[1]=1 must not feed 1→2 in that same round. A second complete round makes cost two feasible. For five stairs W(0..5)=[1,1,2,3,5,8], with W(0)=1 representing the empty path. For costs [10,15,20], arrival costs D(0..3)=[0,0,10,15], and the top is position 3. For houses [2,7,9,3,1], prefix optima are [0,2,7,11,11,12]; skipping can preserve a prior optimum. On the circle [2,3,2], the linear endpoint total 4 is infeasible: both endpoint-excluding paths yield 3. With coins [1,2] and target 3, unordered counting gives two multisets, while ordered stair-style counting gives three paths. For cars and [car,ca,rs], ca|rs succeeds after the longest local word car fails. For [3,5,6,2,4], minimum tails end at [2,4,6] but a witness of length three is [3,5,6]. LCS(abc,ac)=2; edit distance(a,b)=1 even though insertion/deletion-only distance is two. Unique Paths on 3×3 has count rows [1,1,1], [1,2,3], [1,3,6], while Minimum Path Sum must seed actual boundary charges. Partition [1,2,5] has no subset totaling four; an ascending in-place scan would falsely reuse the single 1. Decode Ways for 101 has prefix counts [1,1,1,1], while 100 ends at zero. For [-2,3,-4], endpoint (maximum,minimum) pairs are (-2,-2), (3,-6), (24,-12). Counting Bits through five gives [0,1,1,2,1,2]; seven has more one bits than eight, so counts are not monotone. For exponent ten (binary 1010), consume only the factors for powers two and eight. Widen a negative int exponent before negating MIN_VALUE.

Where the reasoning fails

Zero/negative denominations break termination and smaller-dependency reasoning. Integer.MAX_VALUE+1 can overflow a sentinel. Counting combinations is a different state/transition, and a descending amount loop is needed for 0/1 usage. k stops permits k+1 flights. Promote k before adding one. Nonnegative fares permit a simple-path cap of n−1 edges; negative fares invalidate that cap. A target becoming reachable is not a fixed point, and city-only visited flags discard useful remaining-budget states. A numeric prefix optimum need not include its last house. Shifting a rolling register too early can combine adjacent houses or lose a counting predecessor. A singleton circle has no distinct neighbor and must be handled before excluding endpoints. Empty stair counting returns one; empty cost and robbery optima return zero. Exact Java long results need an explicit bound: the counting reference allows n≤91, while cost/money arrays allow at most 100000 nonnegative int entries. A trie prefix without a terminal is not a complete word. Strict LIS needs the first tail ≥x, so equal values replace rather than extend. The final tails array and a final score row do not retain traceback decisions. LCS zero boundaries must not be copied into edit distance, whose boundaries count insertions/deletions. State whether strings use UTF-16 code units, code points, or graphemes; these references explicitly use code units. Different empty conventions must remain separate from internal identities: an existing 1×1 grid has one empty route, a zero grid dimension has no route, empty partition is true, and public empty decoding is zero despite internal D(0)=1. A minimum-cost row must not read uninitialized zeros as free paths. Maximum-product state must forbid empty intervals and preserve both old extremes. BigInteger keeps exact values but does not make arithmetic or storage constant in bits. Counting Bits needs n+1 output entries including zero; constant scalar workspace does not make total output storage constant. Floating repeated squaring is logarithmic in operations but not automatically correctly rounded; reciprocal-first normalization and overflow/underflow policies are part of its contract.

Reconstruct the reasoning

Write the state sentence, base, recurrence, evaluation order, proof, and complexity before code. Then add a predecessor array to reconstruct one optimum. Compare an exact-edge DP table with rolling at-most layers on the same flight graph. Explain the carry term, demonstrate an input-order bug from in-place relaxation, and identify the history needed to reconstruct an itinerary. Contrast the enumerated row outputs of DSA-122/123 with minimum-coin and combination-count DP. A remaining-sum state alone cannot stand for an arbitrary enumeration prefix when candidate availability or occurrence supply differs. Derive and label the full tables for DSA-126–129 before compressing them. Explain the empty bases, when a charge is paid, and both old register meanings. Then reconstruct one optimum using stored predecessors and explain why value-only constant space does not already provide a witness. Show a three-house circle where whole-array linear DP violates endpoint adjacency. Derive DSA-131–135 from counted/recognized/optimized objects before coding. Swap the two coin-count loops on a small example, build the word-boundary DAG, and produce an LIS whose tails are not a witness. For each alignment cell, name which values belong to the previous versus current row. Finally describe the extra history required for one subsequence or edit script and the effect of swapping axes on operation direction. Finish DSA-136–140 by deriving each state sentence, valid boundary, aggregation and live dependency frontier. Compare ascending reusable-coin updates with descending one-use subset updates. Prove the zero rules in decoding, and show why a maximum product needs a minimum as well. Then describe witness reconstruction separately from the value-only space bound. Derive the binary-parent count recurrence and the exponent parity identity separately. Explain why the former retains a table while the latter needs only scalar state, and why an ideal algebraic invariant does not erase floating-point rounding.

Apply this foundation

Your study notes