Dynamic programming basics
Computer Science · Algorithms
Question 1 of 10
0The base case of a DP recurrence is:
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Dynamic programming basics explained
Dynamic programming solves a problem by breaking it into smaller overlapping subproblems and storing each answer so that it is computed only once. It works when the best answer to the whole problem can be built from the best answers to its smaller parts.
Many recursive solutions repeat the same work. Dynamic programming avoids this by memoization, which stores each subproblem's result the first time it is solved, or by tabulation, which fills a table from the smallest subproblem upward.
A problem suits the method when it has two properties. Overlapping subproblems means the same smaller question comes up many times. Optimal substructure means the best solution can be assembled from best solutions to its parts.
A classic example is making change. Let be the fewest coins needed to make amount . Then , and is the minimum of over every coin that is no larger than . Each entry depends only on earlier entries, so the table is filled in order.
Worked example
Coins worth 1, 3 and 4 units are available (a hypothetical coin set). Find the fewest coins that make amount 6.
- , and (1 + 1).
- , using one 3-unit coin.
- , using one 4-unit coin.
- , using 4 + 1.
- , using 3 + 3.
The answer is 2 coins. Taking the largest coin first would give 4 + 1 + 1, which uses 3 coins, so that simple rule is not optimal for this set.
What you will practise
100 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- Dynamic programming solves problems by:
- Memoisation:
- DP requires problems to have:
- Fibonacci computed with memoisation is:
- Top-down DP is:
- In bottom-up dynamic programming, subproblems are solved:
- The 0/1 knapsack problem asks for:
- The state space of a DP solution is:
…and 92 more.