Dynamic programming basics

Computer Science · Algorithms

Question 1 of 10

0

    The base case of a DP recurrence is:

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    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 dp[a]dp[a] be the fewest coins needed to make amount aa. Then dp[0]=0dp[0] = 0, and dp[a]dp[a] is the minimum of dp[a−c]+1dp[a-c] + 1 over every coin cc that is no larger than aa. 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.

    1. dp[0]=0dp[0] = 0, dp[1]=1dp[1] = 1 and dp[2]=2dp[2] = 2 (1 + 1).
    2. dp[3]=1dp[3] = 1, using one 3-unit coin.
    3. dp[4]=1dp[4] = 1, using one 4-unit coin.
    4. dp[5]=min⁡(dp[4]+1, dp[2]+1, dp[1]+1)=min⁡(2,3,2)=2dp[5] = \min(dp[4]+1,\ dp[2]+1,\ dp[1]+1) = \min(2, 3, 2) = 2, using 4 + 1.
    5. dp[6]=min⁡(dp[5]+1, dp[3]+1, dp[2]+1)=min⁡(3,2,3)=2dp[6] = \min(dp[5]+1,\ dp[3]+1,\ dp[2]+1) = \min(3, 2, 3) = 2, 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.