There are three useful distinctions between dynamic programming and a conventional divide-and-conquer algorithm.
- A divide-and-conquer algorithm typically splits one instance into mostly separate smaller instances; dynamic programming deliberately recognizes overlapping subproblems that recur along different decision histories.
- A dynamic programming state is solved once and its result reused through a table or memoization. A direct divide-and-conquer algorithm normally combines the results of its recursive children without retaining a table indexed by all repeated states.
- The dependency structure of a direct recursive decomposition is a recursion tree; dynamic programming evaluates a Directed acyclic graph of states in dependency order, either bottom-up or by memoization. Its cost is the number of distinct states times the work per state, rather than the number of occurrences in the expanded recursion tree.
These are paradigm-level distinctions, not mutually exclusive definitions: a recursive algorithm can use memoization, and dynamic programming need not be implemented iteratively. For optimization, the dynamic programming state and optimal substructure justify combining stored optimum values; storing repeated work alone does not prove the state is sufficient.
Use unit-cost insertion, deletion and substitution of one symbol. Their minimum total cost is the edit distance. Let be the edit distance between the first symbols of the first sequence and the first of the second. Initialize and . For computeThe cases delete the final source symbol, insert the final target symbol, or align the two final symbols, paying one for substitution and zero for a match. Every optimal alignment ends in one of these cases, and each case extends a valid shorter alignment. Induction on proves the dynamic programming recurrence correct.
Fill rows or columns in increasing order so every dependency is already available. There are entries with constant work per interior entry: running time for nonempty sequences, or including the boundary cases. The full table has space complexity ; two rows give auxiliary space when only the distance is wanted. Predecessor choices in the full table recover an optimal edit sequence.
During the computation in part i, record an index attaining the minimum at every positive amount. Starting with , print and replace by , continuing until .
Every step decreases the amount and reduces the table entry by exactly one. The printed denominations therefore sum to and their number is exactly , proving optimality. The total running time is , including the output; because denomination is available. The predecessor array adds to the space complexity. This is reconstruction from the dynamic programming certificate, not the largest-denomination greedy algorithm, which need not be optimal for arbitrary denominations.
The printed formula for the edge label has mismatched variable names. The type-correct reading is . Interpret the requested route as a directed walk of consecutive labelled edges, allowing repeated vertices; the distinction from a vertex-simple directed path is discussed below.
Let be the set of vertices reachable from the specified start after reading exactly the first labels. Initialize and updateAfter stages, answer yes exactly when . A directed walk realizing a prefix decomposes into a walk realizing the shorter prefix and one correctly labelled final edge; conversely every such extension is valid. This proves the dynamic programming invariant by induction on . Store reachable vertices in Boolean arrays and scan the edges per stage. The running time is with rolling-table space complexity, in addition to graph storage. The empty label sequence is realized by staying at .
If “path” is instead required to mean vertex-simple, augment the state to , where is the set of visited vertices. Start with and extend a matching edge to only when , replacing by . This gives an exact dynamic programming algorithm for that interpretation too; reject immediately when . A straightforward bound is running time with rolling-table storage. The exponential distinction is substantive: all labels equal and include the Hamiltonian path problem from a fixed start. The efficient layered recurrence answers the consecutive-edge interpretation without pretending to enforce distinct vertices.
Write for , with a separate unit denomination. Choose, among all minimum-coin representations of the target, one whose vector of counts is lexicographically largest when larger denominations come first. Such a choice exists because a fixed positive target has only finitely many representations.
There cannot be two unit coins: replacing them by one decreases the count. For , two copies of can be exchanged usingThis keeps the coin count unchanged but increases the first differing larger-denomination count, contradicting the chosen lexicographic maximum. Thus there exists an optimal representation using at most one of each denomination below the largest. The largest denomination may repeat.
It remains to show why that normalization implies greedy optimality; uniqueness alone is not enough for an arbitrary coin system. Fix a denomination . Let be the total value of all coins smaller than in the chosen optimal representation, and let be their number. These smaller coins are distinct. If records the selected non-unit denominations, thenIf , replace all smaller coins by one and unit coins. The new number of coins iscontradicting optimality. Therefore the total value below every denomination is strictly less than .
At the largest denomination, this forces its count to be : its residual value is nonnegative and smaller than . Remove those coins. The same smaller-denomination property then forces the next quotient, and so on down to the unit coin. These are exactly greedy's choices, proving greedy is optimal for every positive target. The argument also covers , where the denominations are two and one. Independent comparison with coin-change dynamic programming confirmed the formula for all and targets from one to 2,000; that finite check supplements the proof.
Use positive integral item weights and a nonnegative integral capacity. For the unbounded knapsack problem, define to be the best value with total weight at most . ThenThe zero candidate is the empty selection, so unused capacity is allowed and an empty set of fitting items causes no problem. Every nonempty feasible selection has some last item ; removing one copy leaves a feasible solution at capacity . Its value is bounded by the corresponding candidate. Conversely, taking an optimal smaller selection and adding that item attains the candidate, proving the recurrence relation by optimal substructure. Positive weights make every dependency strictly smaller.
Fill capacities in increasing order. There are entries, each scanning items, so the dynamic programming takes time and storage. A winning item pointer at each capacity reconstructs the chosen multiplicities. These are capacity-dependent, pseudopolynomial bounds. For zero-weight items, any positive value makes the repetition problem unbounded; nonpositive-value zero-weight items may simply be discarded before using the recurrence.
This version of Kadane's algorithm, named for Joseph Born Kadane, permits the empty subsequence. For , let be the maximum of zero and the weight of a contiguous subsequence ending exactly at position . Let be the best weight anywhere in the first positions. UseA segment ending at either extends one ending at or starts at ; the zero candidate permits discarding a negative predecessor and the empty answer. Any best segment of the first positions either ends at or already occurs in the first . These two decompositions prove the dynamic programming equations by induction.
Here is an implementation returning endpoints, using zero-based indexing:There is exactly one addition per input element, hence additions and comparisons. Auxiliary storage is . The all-negative case retains interval and weight zero. The example returns and weight 8, hence the desired contiguous subsequence.
best_segment(a):
end_weight = best_weight = 0
start = best_lo = best_hi = 0
for j in range(len(a)):
trial = end_weight + a[j]
if trial <= 0:
end_weight = 0
start = j+1
else:
end_weight = trial
if end_weight > best_weight:
best_weight = end_weight
best_lo, best_hi = start, j+1
return (best_lo, best_hi, best_weight)First run breadth-first search, ignoring weights, to obtain the minimum number of edges from the source to each reachable vertex. Then compute weighted distances only along edges that advance one breadth-first layer:Unreachable vertices keep distance . For an undirected graph, scan both orientations of each edge.
d[source] = 0; all other d[v] = infinity
for u in nondecreasing BFS-layer order:
for each outgoing edge (u,v):
if h[v] == h[u]+1:
if d[u]+w(u,v) < d[v]:
d[v] = d[u]+w(u,v)
predecessor[v] = uTo justify discarding other routes, a shortest path can be taken simple because every weight is positive. A simple path of edges has weight inEvery path with at least edges weighs at least . Consequently every minimum-weight path must also have the minimum possible number of edges: this is minimum-hop dominance for nearly unit weights.
A minimum-hop path to uses exactly edges. Every prefix of such a path must itself have minimum hop count, since replacing a longer prefix by a shorter one would shorten the whole route. Hence it advances from layer to layer at every step. The retained edges form a Directed acyclic graph, ordered by . The displayed dynamic programming recurrence therefore finds the cheapest of all minimum-hop paths, which by the preceding bound is a true shortest path.
With an adjacency list, both the breadth-first search and the layer-ordered relaxations take time and total storage, where . The queue order from breadth-first search already supplies the layer order; no sorting or priority queue is needed. This improves the usual binary-heap Dijkstra bound and is linear in the input size.
Let , , and let be the minimum number of words chosen from , in their given order, whose concatenation equals the length- prefix of a list of . Use for impossibility. The boundary values areFor ,Here denotes indices . The first case omits . In the second, the last selected word is , so removing it leaves a solution using only earlier words for the shorter prefix. These are exhaustive alternatives. Conversely either alternative constructs a valid solution, proving the dynamic programming recurrence. Even an empty word causes no cycle because both alternatives use row .
Fill rows in increasing and store the chosen alternative for every finite entry. If , report no solution. Otherwise trace back from : a skip moves to ; a take records index and moves to . Reverse the recorded indices to obtain the required subsequence. Ties may choose either valid predecessor.
There are states. A substring comparison costs , so under the given bounds and the running time is , with storage including reconstruction choices. Two rows give working storage if only the optimum count is needed. For the source example, the optimum is three words, indices , whose concatenation is
010111. This is ordered word concatenation dynamic programming. Postorder traversal 2026-10-31
Visit all child subtrees before visiting their parent. A depth-first traversal of a tree produces this order by processing a node on return from its recursive calls. It lets dynamic programming use the already computed answers of every child subtree.
Profile dynamic programming 2026-10-20
A dynamic programming method that advances a boundary across a structured object and records only the information needed on that boundary. For tilings by pieces of bounded height, a bit mask recording occupied cells in a few frontier rows can determine every legal continuation. Its state space is typically exponential in the width but independent of the total height.
Pseudo-polynomial time Created 2026-10-14 Updated 2026-10-20
An algorithm has pseudo-polynomial time when its running time is bounded by a polynomial in the numerical magnitudes of input quantities, rather than necessarily in their encoded length. The dynamic programming table for the 0-1 knapsack problem uses arithmetic operations for items and capacity . A binary numeral system encoding needs only bits for that capacity, so the table bound can be exponential in the number of capacity bits. This distinction does not claim that every input requires exponential work.
For integer weights, subset-sum dynamic programming finds the greatest achievable total at most in time , where is the total weight. For rational weights and , scale by and round down to . The scaled total is at most , so exact dynamic programming costs arithmetic operations. Lifting its partition to the original weights increases the maximum load by at most . Thus it is a fully polynomial-time approximation scheme for this two-bin problem. Bit complexity also accounts for the rational input and epsilon encodings.
Stochastic control Created 2026-10-07 Updated 2026-10-14
A stochastic control problem chooses an admissible control input using information available in a filtration to optimize an expected objective for a random dynamical system. Dynamic programming often characterizes its value function through a Hamilton-Jacobi-Bellman equation.
Strictly increasing subsequence 2026-10-14
A strictly increasing subsequence selects indices of a sequence with . Equal values cannot both occur in it. Its maximum possible length is , with ; in general for the weak longest increasing subsequence. Use strict comparisons in the dynamic programming recurrence relation and replace the first tail at least as large as the next value in the binary search algorithm.
Synchronous Bellman-Ford recurrence 2026-10-18
For the single-source problem, let be the minimum cost of a directed walk from to using at most edges. Set and for , use for finite , and let a minimum over an empty set be . ThenEvery entry on the right comes from the previous round, requiring separate old and new arrays. The proof is the last-edge decomposition: a permitted directed walk either already uses at most edges, or ends with some after a prefix using at most . Conversely, each candidate describes a permitted directed walk. This dynamic programming viewpoint gives an exact meaning to every intermediate label, even when negative-cost directed cycles exist. Apply the formula to the source too: its initial zero is not a permanent constraint.
If no negative-cost directed cycle is reachable from , removing repeated-vertex portions of a directed walk cannot increase its cost. Whenever a destination is reachable, some shortest directed path therefore uses at most edges, and . Unreachable vertices keep distance . For in-place passes, every finite label still comes from a discovered directed walk; moreover, pass has offered every prefix of length of a shortest directed path, regardless of scan order. Its labels can improve faster than the synchronous labels, while the same upper bound on passes remains valid. This is why repeated local corrections eventually settle a global shortest path problem.
Totient chain 2026-10-20
The sequence obtained by iterating Euler's totient function on a positive integer. Since for , the sequence reaches 1. Counting both endpoints gives the length recurrence relation and ; increasing order of therefore suffices for dynamic programming.
Treewidth 2026-10-25
The minimum width of a tree decomposition. A tree has width at most one, while a clique of vertices forces width at least . Every pair of vertices in the clique shares a bag; their connected bag connected subgraphs of a tree have a common intersection by the Helly property of connected connected subgraphs of a tree, placing the whole clique in one bag. Small treewidth is useful for dynamic programming on finite-domain constraint satisfaction problems.
Weighted interval scheduling 2026-10-18
Weighted interval scheduling assigns each job a reward and maximizes their sum over compatible jobs. Earliest finish can fail for this different objective function; dynamic programming can compare alternatives.[ref]
Lecture 1: Introduction. 6.046J Design and Analysis of Algorithms, Spring 2015; Printed pp. 4–5, Weighted Interval Scheduling and Dynamic Programming
For a separate two-job example, let have reward one and reward ten. Earliest finish accepts and rejects , earning one; the optimum accepts , earning ten. Replacing by preserves job count but loses reward. Thus the interval scheduling exchange argument proves the unit-value theorem only: its preserved quantity must match the intended objective function.
