Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming/Unbounded Knapsack

Learn the pattern · ~14 min

Unbounded Knapsack

also called coin change, complete knapsack

Keep one answer per amount, and build each amount from "amount minus one coin", walking amounts upward so the same coin can be used again.

Signalscoins / pieces with unlimited supplyminimum count or number of ways to reach a totalLearn first0/1 Knapsack
Cheat sheet and practice

Reach for it when you read

  • +"An unlimited supply of each coin / item", "use any number of times", and a target amount.
  • +"Fewest items that add up to exactly X": Coin Change, Perfect Squares.
  • +"How many ways to make X" with reusable pieces: decide whether order matters before writing the loops.
  • +Split a string into pieces from a dictionary where each word may be used again.
  • +Your recursion on (item, amount left) stays on the same item after taking it.

Not this one when

  • ×Each item can be used at most once: 0/1 knapsack, the amount loop runs backward.
  • ×Coins in a nice system (1, 2, 5, 10…) where the problem promises greedy works: then biggest-first is fine, but don't assume it ([1, 3, 4] and 6 break it).
  • ×List every combination, not just count them: backtracking.

Learn Unbounded Knapsack

First, what does "unbounded" mean?

In 0/1 knapsack each item is used once at most. Unbounded means there is no limit: take the same item as many times as you like.

Coins are the standard case. With coins 1 and 3 you can make 6 as 3 + 3, using the 3 twice, or as 1 + 1 + 1 + 3. Taking a coin doesn't use it up. Rod pieces, dictionary words and perfect squares work the same way.

The problem: fewest coins

Coins [1, 3, 4], amount 6. What's the fewest coins that add up to exactly 6? List the mixes by hand:

mix coins how you found it
4 + 1 + 1 3 biggest first: take 4, then 2 is left, only 1s fit
3 + 1 + 1 + 1 4 one 3, the rest in 1s
1 × 6 6 only 1s
3 + 3 2 use the 3 twice

The answer is 2. Biggest-first gave 3: the 4 looked good, but it left a 2 that only 1s could fill. Greedy fails, so we have to weigh the choices.

Take and stay, or skip and move

Line the coins up and stand on one of them. Two moves:

Take the coin and stay on it (there are more of it), or skip it and move to the next coin, never to come back.

Write f(i, amt) for "the fewest coins from coin i onward that make amt":

at what happens next question
coin 1, need 6 take it: 5 left, still on coin 1 1 + f(0, 5)
or skip it: still need 6, now on coin 3 f(1, 6)
need 0 done, no more coins needed 0
no coins left, need > 0 impossible INF

Staying on the coin after taking it is the only difference from 0/1 knapsack, where taking also moves you on.

The brute force: the plain recursion

C++
const int INF = 1e9;                                 // "impossible"; INF + 1 still fits in an int
// f(i, amt) = fewest coins from coins[i..] that make amt
int f(int i, int amt, const vector<int>& coins) {
    if (amt == 0) return 0;                          // made it: no more coins needed
    if (i == (int)coins.size()) return INF;          // no coin types left
    int best = f(i + 1, amt, coins);                 // skip: move to the next coin, never come back
    if (coins[i] <= amt)
        best = min(best, 1 + f(i, amt - coins[i], coins));  // take: stay on the same coin
    return best;
}

It returns 2. Some of the calls it makes (f(i, amt), where i is the coin's position):

  • f(0, 6)
    • take 1: f(0, 5)
      • take 1: f(0, 4)
        • take 1: f(0, 3)
          • skip 1: f(1, 3)← here
    • skip 1: f(1, 6)
      • take 3: f(1, 3)← and here
      • skip 3: f(2, 6)

The full tree has 41 calls for amount 6, and with k coin types it grows like amountᵏ. Coins [1, 2, 5]: amount 1000 makes 3.4 × 10⁷ calls (0.1 seconds), amount 5000 makes 4.2 × 10⁹ (12 seconds), and the problem allows 10⁴. Time limit exceeded.

The one thought: the same question comes back

Look at the arrows. Path one: take 1 three times (3 is left), then skip the 1s. Path two: skip the 1s, take one 3 (3 is left). Both land on coin 3, needing 3.

From there, the past doesn't matter. What's left is "make 3 using coins 3 and 4", and the answer is 1 coin both times. A question is fixed by the pair (i, amt): at most k × (amount + 1) of them. On our input, the 41 calls ask only 27 different questions, and the gap grows fast. Answer each once:

C++
int f(int i, int amt, const vector<int>& coins, vector<vector<int>>& memo) {
    if (amt == 0) return 0;
    if (i == (int)coins.size()) return INF;
    int& m = memo[i][amt];
    if (m != -1) return m;                           // this (coin, amount) was answered before
    m = f(i + 1, amt, coins, memo);
    if (coins[i] <= amt)
        m = min(m, 1 + f(i, amt - coins[i], coins, memo));
    return m;
}

Bottom-up: one row, walked forward

Now fill from the small end. dp[a] = the fewest coins for amount a using the coins seen so far. Bring coins in one at a time; for each, walk the amounts and ask "is a − c plus this coin better?"

C++
int coinChange(const vector<int>& coins, int amount) {
    vector<int> dp(amount + 1, INF);                 // dp[a] = fewest coins for amount a
    dp[0] = 0;
    for (int c : coins)
        for (int a = c; a <= amount; a++)            // forward: coin c may be used again
            dp[a] = min(dp[a], dp[a - c] + 1);
    return dp[amount] >= INF ? -1 : dp[amount];
}

Here is coin 3 arriving, when the row (only 1s so far) is 0, 1, 2, 3, 4, 5, 6:

a reads dp[a − 3] what happens dp[a]
3 dp[0] = 0 one 3 beats three 1s 1
4 dp[1] = 1 3 + 1 beats four 1s 2
5 dp[2] = 2 3 + 1 + 1 beats five 1s 3
6 dp[3] = 1 dp[3] was just set by this coin: 3 + 3 2

That last row is the whole point. Going forward, dp[a − c] may already include coin c, so the coin gets reused. That's what unbounded wants. (0/1 knapsack walks backward for exactly the opposite reason.)

The whole table:

after coin what happens dp[0..6]
1 every amount in 1s 0, 1, 2, 3, 4, 5, 6
3 3s replace groups of three 1s 0, 1, 2, 1, 2, 3, 2
4 4 and 4 + 1 get shorter 0, 1, 2, 1, 1, 2, 2

2, the same answer as the brute force. If an amount stays INF, nothing makes it: coins [2] and amount 3 return −1.

Why it's O(coins × amount)

Count the cells: each coin visits each amount once, with one min. That's O(k × amount) time, 1.2 × 10⁵ steps for 12 coins and amount 10⁴. One row: O(amount) space.

From amountᵏ calls down to k × amount cells, because only "which coin, how much left" matters.

Count the ways? Add instead of min

Coin Change II asks how many mixes make 6. Swap min for +, and seed ways[0] = 1 (one way to make 0: no coins):

C++
vector<long long> ways(amount + 1, 0);
ways[0] = 1;                                 // one way to make 0: no coins
for (int c : coins)                          // coins outside: each mix counted once
    for (int a = c; a <= amount; a++)
        ways[a] += ways[a - c];
after coin ways[0..6]
1 1, 1, 1, 1, 1, 1, 1
3 1, 1, 1, 2, 2, 2, 3
4 1, 1, 1, 2, 3, 3, 4

The 4 mixes: 1+1+1+1+1+1, 3+1+1+1, 3+3, 4+1+1. Why is 3+1+1+1 not also counted as 1+3+1+1? With the coins outside, every mix is built in one fixed order: all its 1s, then its 3s, then its 4s. It's the recursion's rule again: once you skip a coin, you never come back.

Order matters? Swap the loops

Combination Sum IV counts 3+1+1+1 and 1+3+1+1 as different. Put the amount outside, so any coin can be the last one added:

C++
vector<long long> ways(amount + 1, 0);
ways[0] = 1;
for (int a = 1; a <= amount; a++)            // amount outside: any coin can come last
    for (int c : coins)
        if (c <= a) ways[a] += ways[a - c];

Now amount 6 gives 9: 4 orders of 3+1+1+1, 3 of 4+1+1, plus 3+3 and 1×6. Same numbers, different question, different loop order.

Perfect Squares? Make the coins yourself

The fewest perfect squares that sum to 12: the coins are 1, 4, 9, then it's Coin Change.

C++
vector<int> squares;
for (int k = 1; k * k <= n; k++) squares.push_back(k * k);   // the coins: 1, 4, 9
int answer = coinChange(squares, n);

The answer is 3 (4 + 4 + 4). Biggest-first takes 9 + 1 + 1 + 1, which is 4.

Remember this

  • "Unlimited supply", "use any number of times": take-and-stay in the recursion, the amount loop forward in the table.
  • Coins outside counts combinations; amount outside counts orders. Read which one the problem wants before writing the loops.
  • Use a safe INF (1e9, so INF + 1 doesn't overflow) and return −1 if the amount stays unreachable.
  • Whenever a problem builds a target from reusable pieces, fewest or how many ways, it's unbounded knapsack.

Practise it on Coin Change, then Perfect Squares (make the coins), Coin Change II (count combinations), Combination Sum IV (count orders) and Word Break (the pieces are words, and order matters).

Below, watch Coin Change run line by line.

Watch it work, line by line

Coin Change ↗, coins = [1, 3, 4], amount = 6 → 2 (3 + 3). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Can each item be used any number of times, and is the target small enough to give every amount its own cell?

Reach for it when

  • +coins / pieces with unlimited supply
  • +minimum count or number of ways to reach a total
  • +amount up to ~1e4-1e6

It fails when

  • ×Each item usable only onceuse 0/1 knapsack (loop capacity backward)
  • ×Amounts/weights are gigantic, so O(n·T) blows upuse Math / number theory
  • ×You think greedy coin change is optimal: only for canonical coin systems, rarely guaranteeduse Trust the DP unless canonical is stated

Looks like it, isn't (and the other way round)

  • Coin Change looks like Greedy, needs this pattern

    Largest-coin-first fails for arbitrary denominations.

  • Combination Sum IV looks like Subsets / Permutations / Combinations, needs this pattern

    Only the count is asked and order matters: dp over amounts with amount as outer loop.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Which direction does the capacity loop go in unbounded knapsack, and why?Reveal

    Forward. Then dp[a - c] may already use coin c, which is allowed because coins are unlimited.

  • 2Coins outside or amounts outside: which counts 1 + 2 and 2 + 1 once?Reveal

    Coins outside counts combinations (once). Amounts outside counts every order.

  • 3Why doesn't greedy work for coins 1, 3, 4 and amount 6?Reveal

    It takes 4 + 1 + 1 = 3 coins, but 3 + 3 = 2. Greedy is only safe for special coin systems.

  • 4For counting, coins outside or amounts outside: which counts 1 + 3 and 3 + 1 once, and why?Reveal

    Coins outside: each combination is built in one fixed order of coin types, so it's counted once. Amounts outside decides the last coin at every step, so every order is its own path.

Practice ladder

every problem →
  1. 1Coin Changethe hookMedium
  2. 2Minimizing Coinssame frame, big inputEasy
  3. 3Perfect Squaresmake the itemsMedium
  4. 4Coin Change IIcount combinationsMedium
  5. 5Coin Combinations IIcount combinationsMedium
  6. 6Combination Sum IVcount ordersMedium
  7. 7Coin Combinations Icount ordersEasy
  8. 8Word Breakitems are wordsMedium

Finished Unbounded Knapsack? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Unbounded Knapsack

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial