This site uses one functional cookie to keep feature rollouts consistent for you. Nothing is set until you choose. See the privacy notice.
Phase 4: Optimisation
Define what dp[i] means, find how it depends on smaller i, then fill it in order.
Builds on Backtracking.
The question to ask
Can I say in one sentence what dp[i] means, and build it from dp of smaller i?
DP is recursion where the same subproblems keep coming back, so you remember their answers. The work is entirely in the definition: say in words what dp[i] means ("the most money robbing houses 0..i"), write how it follows from smaller indices, set the base cases, and fill left to right. Questions asking for a count of ways, a minimum, a maximum or a yes/no over choices, where greedy has a counter-example, are DP. Start from the brute-force recursion, add a memo, then turn it into a table if you have time.
Want to watch it run first? Step through the interactive walkthrough.
Time O(n × choices per step) · Space O(n), often O(1) with rolling variables
Write it from memory first, in an editor or on paper, then check. Recalling it is what makes it stick; reading it again mostly doesn't.
dp[a] is the fewest coins making amount a. Every coin is a choice that leaves a smaller amount. Infinity marks amounts that can't be made, and survives the + 1 unchanged.
function coinChange(coins: number[], amount: number): number {
const dp = new Array<number>(amount + 1).fill(Number.POSITIVE_INFINITY);
dp[0] = 0;
for (let a = 1; a <= amount; a++) {
for (const coin of coins) {
if (coin <= a) dp[a] = Math.min(dp[a], dp[a - coin] + 1);
}
}
return dp[amount] === Number.POSITIVE_INFINITY ? -1 : dp[amount];
}dp[i] is the length of the longest increasing subsequence ending at index i, so it looks back at every smaller value. O(n²); patience sorting with binary search is the O(n log n) follow-up.
function lengthOfLIS(nums: number[]): number {
const dp = new Array<number>(nums.length).fill(1);
for (let i = 1; i < nums.length; i++) {
for (let j = 0; j < i; j++) {
if (nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
return Math.max(0, ...dp);
}dp[i] is true when the first i characters split into dictionary words. Check every cut j where dp[j] holds and s.slice(j, i) is a word.
function wordBreak(s: string, wordDict: string[]): boolean {
const words = new Set(wordDict);
const dp = new Array<boolean>(s.length + 1).fill(false);
dp[0] = true;
for (let i = 1; i <= s.length; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && words.has(s.slice(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length];
}Easy to hard. Read the prompt and name the signal before opening the tell. After each attempt, rate it: Again brings it back tomorrow, Hard holds the interval, Good and Easy push it further out.
You climb 1 or 2 steps at a time. In how many distinct ways can you climb to the top of n steps?
"How many distinct ways" to "climb": ways(n) = ways(n - 1) + ways(n - 2). Fibonacci in disguise.
Not attempted yet
Each step has a cost and you climb one or two steps after paying. Return the minimum cost to reach the top, starting from step 0 or 1.
Stairs again, with min instead of sum: dp[i] = cost[i] + min(dp[i - 1], dp[i - 2]).
Not attempted yet
Houses hold money but robbing two adjacent houses alerts the police. Return the maximum amount you can rob.
"Adjacent houses" and "maximum amount": rob this one plus best from two back, or skip it.
Not attempted yet
The houses are arranged in a circle, so the first and last are adjacent houses. Return the maximum amount you can rob.
A circle means you can't take both ends: run House Robber twice, once without the first house, once without the last.
Not attempted yet
Find the contiguous subarray with the largest sum and return its sum.
"Contiguous subarray" with the "largest sum": Kadane's. The best ending here is this value, or this value plus the best ending one before.
Not attempted yet
Given coin denominations and an amount, return the fewest coins that make up the amount, or -1.
"Fewest" coins: greedy fails on [1, 3, 4] for 6. dp[a] = 1 + min(dp[a - coin]).
Not attempted yet
Return the length of the longest strictly increasing subsequence.
"Longest increasing subsequence": dp[i] ending at i is O(n²); the binary search tails array is O(n log n).
Not attempted yet
Can the string be segmented into a space-separated sequence of one or more dictionary words?
"Segmented" into words: dp[i] is whether the first i characters can be, checking every last word.
Not attempted yet
Letters map to '1' to '26'. Given a digit string, return the number of ways to decode it.
"Number of ways" to "decode": stairs where a step is one valid digit or two. Watch the zeros.
Not attempted yet
Can the array be split into two subsets with equal sum?
"Equal sum" halves: can some subset reach total / 2? 0/1 knapsack over a boolean array, iterating sums downwards.
Not attempted yet
Find the contiguous subarray with the largest product and return the product.
A "contiguous subarray" product where a negative flips the order: track both the max and min ending here.
Not attempted yet
Return the longest palindromic substring of s.
Expand around each of the 2n - 1 centres, O(n²) time and O(1) space. The dp table over (i, j) is the textbook alternative.
Not attempted yet
Count how many palindromic substrings the string contains.
Counting each "palindromic substring": expand around every centre and count as you go.
Not attempted yet