Dynamic programming
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 order
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 minimization per cell costs .
For a DAG with terminal , the fewest unit-cost steps to the terminal satisfy and in reverse topological order, with for a vertex unable to reach . For a number-line shortcut, include both the next ordinary position and the shortcut destination as candidate successors.
6.2 Longest common subsequence
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 have lengths and be the LCS length of prefixes .
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 order
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 have dimensions , for .
There are complete binary parenthesizations for 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 sum
Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks
Item has positive integer weight and nonnegative value . Capacity is a nonnegative integer in the same weight unit. Let be the best value from the first items at capacity ; 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 , not zero. These are different problems from “weight at most capacity”.
6.5 Rod cutting and unbounded choices
Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks
For a rod of integer length , price is obtained by selling a piece of integer length . Prices are per piece, not per metre. With no cutting cost and no scrap, the chosen lengths must sum to .
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 windows
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 distinct values, advance the right pointer, count the new value, and advance the left pointer until at most counts are positive. Each pointer moves at most times; with constant-time dictionary operations the scan is . 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 subsequences
Past papers · CS 2014–2026 (23 papers): 1 question, 1 mark
Let be the input and the longest strictly increasing subsequence ending at . This is not the length of a contiguous increasing run.
For length computation, store the smallest possible tail value for every achievable length. Use the first tail for strict increase; use the first tail 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.