Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 19

Dynamic Programming for Unbounded Knapsack-like Problems

This lesson is built with resources from youtube.com, hello-algo.com and 1 more site.

Introduction

Welcome to the first lesson in our module on Core Dynamic Programming Patterns. In the previous module, you built a strong foundation in DP mechanics, culminating in a deep dive into space optimization techniques. You saw how the dependency structure of a recurrence relation dictates whether you can reduce space, and more subtly, how it determines the required iteration order (e.g., right-to-left for 0/1 Knapsack).

Today, we'll apply these concepts to a fundamental DP pattern: unbounded choice problems. The learning outcome is to solve unbounded choice problems using DP, with canonical examples like Coin Change and Rod Cutting.

In these problems, you're given a set of items that you can use an infinite number of times to achieve a certain goal. This "unbounded" nature leads to a specific recurrence structure that is crucial to master. For a Staff-level interview, recognizing this pattern and fluently moving between its variations (minimization, maximization, counting) is a key signal of proficiency.

Let's begin by establishing the general framework for this pattern, known as the Unbounded Knapsack Problem.


1. The Unbounded Knapsack Framework

The Unbounded Knapsack problem is the archetype for unbounded choice problems. It's defined as follows:

Given items, each with a weight and a value , and a knapsack with a maximum capacity . You have an infinite supply of each item. Find the maximum possible value of items you can fit into the knapsack.

The key difference from the 0/1 Knapsack problem is the "infinite supply." This small change has a significant impact on the state transition.

Let's define our 2D DP state: represents the maximum value achievable using the first items with a knapsack capacity of .

When considering item , we have two choices for a given capacity :

  1. Don't include item : In this case, the maximum value is simply the best we could do with the first items and the same capacity . This is .
  2. Include item : We add item to the knapsack. Its value is (using 0-based indexing for arrays). The remaining capacity becomes . Crucially, because we have an unlimited supply, the subproblem for the remaining capacity can still consider all of the first items, including item itself. The value is .

Notice the subtle but powerful difference in the second choice compared to a 0/1 knapsack. We recurse on , not , because item is still available.

This gives us the state transition equation:

Unbounded Knapsack Dynamic Programming Tabulation Table
This DP table illustrates the tabulation process for an unbounded knapsack problem. Each cell `dp[i][c]` is computed by comparing the value from the cell above (not taking item `i`) with the value obtained by taking item `i` and looking up the solution for the remaining capacity in the *current* row.

For a formal definition and a Go implementation of this 2D DP approach, the following resource is excellent.

Unbounded Knapsack Problem

The 'Hello Algo' guide provides a clear definition of the Unbounded Knapsack problem, its state transition equation, and a clean 2D DP implementation in Go.

Please read section '14.5.1 Unbounded Knapsack Problem', focusing on the state transition logic and the Go code example. This establishes the foundational 2D solution.


2. Space Optimization: The Forward-Order Traversal

As you learned in the previous lesson, a recurrence that depends only on the previous and current rows is a prime candidate for space optimization. Our Unbounded Knapsack recurrence fits this description perfectly. We can reduce the space complexity from to .

Here's where the connection to the last lesson becomes critical.

  • For the 0/1 Knapsack, the recurrence is . Because both choices depend only on the previous row i-1, we must iterate the inner capacity loop from right-to-left to avoid using a value that was already updated in the current pass.
  • For the Unbounded Knapsack, the recurrence is . The "include item" choice depends on the current row i. This means we actually want to use values that have been updated in the current pass. This is achieved by iterating the inner capacity loop from left-to-right (forward order).

This distinction in loop direction is a Staff-level detail that demonstrates a deep understanding of the underlying data dependencies.

Unbounded Knapsack Problem

Let's continue with the 'Hello Algo' guide to see how this forward-order traversal works for space optimization.

Please read section '3. Space Optimization'. Pay close attention to the diagrams comparing the traversal orders and the simplified Go code using a 1D dp array. This is the canonical space-optimized approach.

The resulting space-optimized Go code is clean and efficient. Notice the forward c loop:

// wgt: weights, val: values, cap: capacity
func unboundedKnapsackDPComp(wgt, val []int, cap int) int {
    n := len(wgt)
    dp := make([]int, cap+1) // O(cap) space

    // Iterate through each item
    for i := 1; i <= n; i++ {
        // Iterate through capacities in forward order
        for c := 1; c <= cap; c++ {
            if wgt[i-1] <= c {
                // dp[c] currently holds the value from the previous row (dp[i-1][c])
                // dp[c-wgt[i-1]] holds the value from the current row (dp[i][c-wgt[i-1]])
                // because we are iterating left-to-right.
                dp[c] = int(math.Max(float64(dp[c]), float64(val[i-1] + dp[c-wgt[i-1]])))
            }
        }
    }
    return dp[cap]
}

3. Application: The Coin Change Problem

The Coin Change problem is a classic application of the Unbounded Knapsack pattern. We'll explore its two main variants.

Variant 1: Minimum Number of Coins (LC 322)

Problem: Given an array of coin denominations and a total amount, find the fewest number of coins required to make up that amount.

This is an Unbounded Knapsack problem where:

  • Items are coins.
  • "Weight" of each item is its denomination.
  • "Value" of each item is 1 (we are counting the coins).
  • "Capacity" is the target amount.
  • The goal is to MINIMIZE the total "value" (number of coins).

The most direct solution uses a 1D DP array from the start. Let dp[a] be the minimum coins for amount a.

To understand the logic from the ground up, let's watch this excellent video.

Coin Change - Dynamic Programming Bottom Up - Leetcode 322

This NeetCode video provides a fantastic bottom-up explanation for the 'minimum coins' version of the Coin Change problem.

Please watch from 10:36 to 19:14. The first part (10:36-15:32) explains the bottom-up DP logic, and the second part (15:32-19:14) walks through the code. This is the standard solution expected in interviews.

The logic translates into the following Go code.

  • State: dp[a] = fewest coins to make amount a.
  • Initialization: dp array of size amount + 1, filled with a value representing infinity (e.g., amount + 1). dp[0] is set to 0.
  • Recurrence: For each amount a from 1 to target, we iterate through the coins. If a coin <= a, we update dp[a] = min(dp[a], 1 + dp[a - coin]).
// coinChange finds the minimum number of coins to make a given amount.
func coinChange(coins []int, amount int) int {
    // A value larger than any possible answer, used to signify impossibility.
    max := amount + 1
    
    // dp[i] will be storing the minimum number of coins required for amount i.
    dp := make([]int, amount+1)
    for i := range dp {
        dp[i] = max
    }
    
    // Base case: 0 coins are needed to make an amount of 0.
    dp[0] = 0
    
    // Compute DP values for each amount from 1 to amount.
    for a := 1; a <= amount; a++ {
        // For each amount, try every coin.
        for _, coin := range coins {
            if coin <= a {
                // If we use this coin, the new total is 1 + the solution for the remaining amount.
                dp[a] = min(dp[a], 1 + dp[a-coin])
            }
        }
    }
    
    // If dp[amount] is still 'max', it means we couldn't form the amount.
    if dp[amount] > amount {
        return -1
    }
    return dp[amount]
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

Complexity: Time: , Space: .

Variant 2: Number of Combinations (LC 518)

Problem: Given coins and an amount, find the total number of combinations of coins that make up the amount.

This is a counting problem, so our operator will be + instead of min. However, there's a new challenge: avoiding duplicate combinations (e.g., [1, 2, 2] is the same combination as [2, 1, 2]).

The standard way to solve this is to build the solution one coin at a time. This prevents permutations from being counted as different combinations. The following video explains this crucial concept.

Coin Change 2 - Dynamic Programming Unbounded Knapsack - Leetcode 518 - Python

NeetCode's video on 'Coin Change 2' explains how to structure the DP to count combinations without duplicates. It covers the decision tree, memoization, and the optimized 1D DP.

Please watch from 01:30 to 22:24. This is a comprehensive walkthrough. Pay special attention to: The initial decision tree and how it avoids duplicates by only using coins at or after the current coin's index (01:30 - 07:32). How this translates to a 2D DP table (07:59 - 13:26). The final, space-optimized 1D DP solution (17:11 - end).

The space-optimized solution is particularly elegant.

  • State: dp[a] = number of combinations to make amount a.
  • Initialization: dp array of size amount + 1. dp[0] = 1 (there is one way to make amount 0: by picking no coins).
  • Recurrence: We iterate through the coins one by one. For each coin, we update the dp array for all amounts it can contribute to.
// change finds the number of combinations to make a given amount.
func change(amount int, coins []int) int {
    dp := make([]int, amount+1)
    
    // Base case: There is one way to make amount 0 (the empty set).
    dp[0] = 1
    
    // Iterate through each coin. This ensures we don't double-count permutations.
    for _, coin := range coins {
        // For each coin, update the dp array for amounts it can contribute to.
        // The loop starts from 'coin' because the coin can't contribute to smaller amounts.
        for a := coin; a <= amount; a++ {
            // The number of ways to make amount 'a' is increased by the number
            // of ways to make the remaining amount 'a - coin'.
            dp[a] += dp[a-coin]
        }
    }
    
    return dp[amount]
}

Complexity: Time: , Space: .


4. Generalizing the Pattern: Rod Cutting

The Rod Cutting problem is another classic unbounded choice problem that fits this pattern perfectly.

Problem: Given a rod of length and a list of prices for rod pieces of sizes 1 to , determine the maximum value obtainable by cutting up the rod and selling the pieces.

When we make a cut of length , we are left with a subproblem of solving for the remaining rod of length . This is an unbounded choice because we can cut as many pieces of any given length as we want.

Rod Cutting Problem: Dynamic Programming Approach
This diagram illustrates the Rod Cutting problem's recurrence. To find the optimal value for a rod of length `n`, `Vn`, we consider every possible first cut `i`. The value is the price of that cut, `Pi`, plus the optimal value for the remaining rod, `Vn-i`. We take the maximum over all possible cuts.

The recurrence is:
dp[i] = max value from a rod of length i

This structure is identical to the Coin Change (min coins) problem, just with a max operator and using prices instead of a fixed value of 1.


Conclusion

Today you learned the unbounded choice DP pattern, a cornerstone of solving a wide class of interview problems.

Key Takeaways:

  • Pattern Recognition: Unbounded choice problems involve using a set of items with an infinite supply to optimize some value (min, max, or count) for a given target or capacity.
  • Recurrence Relation: The key feature is that the "take an item" decision leads to a subproblem that can still use the same item. This results in a recurrence like dp[i] = \text{op}(..., dp[i - \text{item_weight}]).
  • Space Optimization: Because the recurrence uses already-updated values from the current pass, the space-optimized 1D DP solution requires a forward (left-to-right) traversal of the inner loop (the capacity/amount loop).
  • Problem Variations: The underlying DP structure remains the same whether you are minimizing coins, maximizing value (Knapsack/Rod Cutting), or counting combinations. Only the operator (min, max, +) and base cases change.

Preview of the Next Lesson:
We will now move to the other side of the coin: 0/1 Knapsack problems. You will see how the simple constraint of "use an item at most once" changes the DP recurrence, which in turn changes the space optimization strategy, requiring the backward (right-to-left) inner loop traversal we teased in the previous module. This contrast will solidify your command over both fundamental knapsack patterns.