Skip to content
DSA in JavaScript
← All patterns

Dynamic Programming

0/30 solved

What it is

Break a problem into smaller overlapping problems, solve each one once and store the result so it is never recomputed.

Used for

Counting ways, minimum or maximum cost, knapsack, longest subsequence, edit distance.
stairs
0
1
2
3
4
5
ways
·
·
·
·
·
·

Step 1 of 6

Goal: how many ways can you climb 5 stairs taking 1 or 2 steps at a time? You reach stair 5 from stair 4 or stair 3, so ways(5) = ways(4) + ways(3). Working that out naively repeats the same sub-questions many times. Instead write each answer down once.

Template

function coinChange(coins, amount) {  const dp = Array(amount + 1).fill(Infinity);  dp[0] = 0;  for (let a = 1; a <= amount; a++)    for (const c of coins) if (c <= a) dp[a] = Math.min(dp[a], dp[a - c] + 1);  return dp[amount] === Infinity ? -1 : dp[amount];}

Practice problems