Chapter 6

Dynamic programmingCS

Choose states so that future possibilities depend only on the state. Write base cases, transitions and evaluation order before counting time. Recovering a solution may need predecessor choices even when the optimal value fits in a small rolling array.

6.1 States and dependency orderCS

Past papers · CS 2014–2026 (23 papers): 2 questions, 4 marks

Top-down memoization evaluates reached states once; bottom-up tabulation evaluates states in an order that respects dependencies. Overlapping subproblems explain the saving over repeated recursion. An optimal-substructure argument explains why the state transition is correct.

If a grid entry depends on its upper and left neighbours, row order, column order or increasing index sum are valid. Scanning an entire grid for each diagonal can be correct yet cubic; enumerating only the cells on each diagonal is quadratic. Likewise, a two-dimensional table with an O(n)O(n) minimization per cell costs O(n3)O(n^3).

For a DAG with terminal tt, the fewest unit-cost steps to the terminal satisfy J(t)=0J(t)=0 and J(v)=1+min⁡(v,u)∈EJ(u)J(v)=1+\min_{(v,u)\in E}J(u) in reverse topological order, with +∞+\infty for a vertex unable to reach tt. For a number-line shortcut, include both the next ordinary position and the shortcut destination as candidate successors.

6.2 Longest common subsequenceCS

Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks

A subsequence preserves order but may skip entries. A substring is contiguous. Let strings X,YX,Y have lengths m,nm,n and L[i,j]L[i,j] be the LCS length of prefixes X[1..i],Y[1..j]X[1..i],Y[1..j].

To count distinct longest subsequences on a small instance, carry sets of optimal strings or explicitly deduplicate the strings generated by backtracking. Counting tied table paths can count the same string several times. Distinguish “distinct strings” from “choices of positions”. Longest common substring instead resets its suffix-length state to zero at a mismatch and takes the maximum over all cells.

6.3 Matrix-chain orderCS

Past papers · CS 2014–2026 (23 papers): 2 questions, 4 marks

Matrix multiplication is associative, but intermediate dimensions change the operation count. The matrices remain in their original order. Let AiA_i have dimensions pi−1×pip_{i-1}\times p_i, for i=1,…,ni=1,\ldots,n.

There are 1n(2n−2n−1)\frac1n\binom{2n-2}{n-1} complete binary parenthesizations for n≥1n\ge1 matrices. An explicitly computed adjacent pair corresponds to a pair of leaf children at a split; reconstruct the selected parenthesization before listing such pairs. Equal costs can produce several optimal orders.

6.4 0/1 knapsack and subset sumCS

Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks

Item ii has positive integer weight wiw_i and nonnegative value viv_i. Capacity WW is a nonnegative integer in the same weight unit. Let K[i,c]K[i,c] be the best value from the first ii items at capacity cc; unused capacity is allowed.

If repeated copies are allowed, the take transition can use the current row; one-dimensional capacities then run upward. For an exact-fill value problem, unreachable states are −∞-\infty, not zero. These are different problems from “weight at most capacity”.

6.5 Rod cutting and unbounded choicesCS

Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks

For a rod of integer length nn, price pip_i is obtained by selling a piece of integer length ii. Prices are per piece, not per metre. With no cutting cost and no scrap, the chosen lengths must sum to nn.

A cost per cut is charged only when the remainder is nonempty. Counting optimal solutions needs a convention: ordered cut sequences and unordered multisets of lengths have different counts. Store sets of sorted length tuples for small counting questions.

6.6 Maximum subarray and sliding windowsCS

Past papers · CS 2014–2026 (23 papers): 2 questions, 3 marks

A subarray uses consecutive indices. For maximum sum, decide whether the current element starts a new interval or extends the best interval ending one position earlier. For constraints such as “at most two distinct values”, keep enough state to remove the left boundary when necessary.

For the longest window with at most kk distinct values, advance the right pointer, count the new value, and advance the left pointer until at most kk counts are positive. Each pointer moves at most nn times; with constant-time dictionary operations the scan is O(n)O(n). For exactly two allowed distinct values, a constant-space state can track the last value, the other value, the current final run length and the current valid suffix length. A new third value retains only the previous final run and the new entry.

6.7 Increasing subsequencesCS

Past papers · CS 2014–2026 (23 papers): 1 question, 1 mark

Let A1,…,AnA_1,\ldots,A_n be the input and LiL_i the longest strictly increasing subsequence ending at ii. This is not the length of a contiguous increasing run.

For O(nlog⁡n)O(n\log n) length computation, store the smallest possible tail value for every achievable length. Use the first tail ≥Ai\ge A_i for strict increase; use the first tail >Ai>A_i for nondecrease. The tails array need not itself be a subsequence. For replacement counting, retain a longest nondecreasing subsequence and fill gaps with compatible equal values. For strict increase with integer replacements, gap sizes impose additional restrictions.

Last-minute recall

  • Define what every DP state means before writing its transition.
  • Work is states times candidate transitions only when that count matches the loops.
  • Dependencies determine the valid fill order.
  • LCS may skip entries; common substring may not.
  • Matrix-chain DP changes parentheses, not matrix order.
  • Descending capacity means each item is used at most once.
  • Rod cutting allows repeated piece lengths.
  • Specify whether an empty subarray is permitted.
  • Strict and nondecreasing subsequences use different inequalities.

Revise offline: the whole Algorithms handbook as one PDF

52 pages · 2.6 MBFree to read online. Sign in to download the PDF.We save the handbook, version and request time in My downloads. Privacy policy

All chapters · Corrections