Algorithms · Dynamic Programming Problem Set: LIS, Edit Distance, Coin Change, Rod Cutting and Counting Strings
The DP Recipe (apply it to every problem below)
This chapter is the "problem gym" that follows the DP basics and LCS chapters. Every problem here is solved with the same six-step recipe, and every table is filled number by number so you can reproduce it in the exam hall. Where a textbook convention differs (0-based vs 1-based, "order p" vs "n"), both are stated.
| Step | Question to ask | What you write |
|---|---|---|
| 1. State | What does one subproblem mean? | Define or in words |
| 2. Recurrence | How does a bigger state use smaller states? | The formula, with every symbol defined |
| 3. Base case | Smallest states with known answers | , , etc. |
| 4. Order | Which direction fills the table so dependencies are ready? | Increasing , increasing , etc. |
| 5. Answer | Which cell (or max/min over cells) is the final answer? | e.g. , or |
| 6. Space | Can rows be discarded? | or rolling array |
Symbols used throughout: = length of a sequence/array; = length of the second string; = capacity; = value; = weight of item ; = value of item ; = coin denomination; = amount.
Two conventions you must fix before writing any table:
| Convention | 0-based | 1-based |
|---|---|---|
| Array indices | ||
| DP table | with , as base | same, but refers to first and first characters |
| GATE usage | Strings/arrays usually 1-based in tables (prefix lengths) | Usual GATE choice: 1-based prefix table |
The prefix table = answer for the first characters of and first characters of is the standard GATE layout. We use it everywhere below.
2.1 Definition and DP
State: = length of the longest increasing subsequence ending at index (the subsequence must include ).
Recurrence:
Answer: (not !).
Time , space .
2.2 Worked example
(1-based).
| Candidates with | |||
|---|---|---|---|
| 1 | 3 | none | 1 |
| 2 | 10 | (), | |
| 3 | 2 | ? no | 1 |
| 4 | 1 | none | 1 |
| 5 | 20 | :1, :2, :1, :1 → max 2 |
Answer . The LIS is . ✔
2.3 patience-sorting method
Maintain an array tails where tails[k] = smallest possible tail of an increasing subsequence of length (0-based tails). For each element , binary-search the first position with tails[pos] >= x and replace it; if none, append.
Length of LIS = size of tails. (The tails array itself is not necessarily a valid LIS — a classic trap.)
Worked on the same array :
| Step | tails before | Action | tails after | |
|---|---|---|---|---|
| 1 | 3 | [] | append | [3] |
| 2 | 10 | [3] | append (10>3) | [3,10] |
| 3 | 2 | [3,10] | replace 3 (first ≥2) | [2,10] |
| 4 | 1 | [2,10] | replace 2 | [1,10] |
| 5 | 20 | [1,10] | append | [1,10,20] |
Size = 3. ✔ Time , space .
Strict vs non-decreasing: for strictly increasing use lower_bound (first ); for non-decreasing LIS use upper_bound (first ). GATE usually means strictly increasing.