Skip to main content

Dynamic Programming Knapsack Problem Solutions

Comprehensive Java implementation of classic knapsack problems including 0/1, unbounded, and bounded variants with optimal time and space complexity analysis.

The knapsack problem represents one of the most fundamental dynamic programming challenges, with applications spanning resource allocation, asset selection, and optimization scenarios across computer science and operations research domains.

1. Pattern Restatement

Clarifying questions to ask the interviewer:

  1. What is the size constraint on the input items? Are we dealing with small arrays (e.g., < 100 items) or potentially large datasets that require efficient algorithms?
  2. Can the input array be mutated? This affects whether we can sort or modify items in-place.
  3. What is the target complexity for follow-ups? Should we aim for O(nW) or O(n log n) time complexity?
  4. Are duplicates allowed in the input items? This impacts whether we can treat items as unique or need to account for multiple instances.
  5. What is the expected return format? Should we return just the maximum value, or also the items selected?

Restatement of the pattern:

The Knapsack problem is a classic optimization problem where we are given a set of items, each with a weight and value, and a knapsack with a maximum weight capacity. The goal is to determine the most valuable combination of items that can fit within the knapsack's weight constraint.

Signal words and constraint shape:

  • "Maximum value" or "optimal combination"
  • "Weight capacity" or "limited resources"
  • "Items with weights and values"
  • "Subset selection" or "choosing which items to include"
  • "0/1 knapsack" (each item can be taken at most once) or "unbounded knapsack" (items can be reused)

Assumptions:

  • Items are discrete and cannot be split
  • Each item has exactly one weight and one value
  • The knapsack capacity is a positive integer
  • We are looking for an optimal solution, not just any valid combination

Scenario suitability:

This pattern is best suited for static scenarios where all items and constraints are known upfront. It's not ideal for streaming data where items arrive continuously, but it can be adapted for online scenarios with precomputed solutions or when the item set is fixed and only capacity changes.

2. When to Use This Pattern

Signal words and constraint shapes in a problem statement that indicate this pattern:

  • "Maximize" or "minimize" objectives with resource constraints
  • "Capacity" or "weight" limits on selection
  • Items with associated values and weights/costs
  • "Subset selection" or "choosing optimal items"
  • Problems asking for maximum value within constraints

Why this pattern fits better than the most common alternatives: The knapsack pattern is uniquely suited for optimization problems where you must make binary choices (include/exclude items) under capacity constraints. Unlike greedy approaches that may fail to find global optimum, or brute force that's exponential, knapsack provides an efficient dynamic programming solution with clear mathematical structure. It's superior to linear programming formulations for discrete selection problems.

Conditions where a variation or related pattern applies instead:

  • If items can be split (fractional knapsack) → use greedy algorithm with value-to-weight ratios
  • If there's no capacity constraint but maximization objective → use standard DP or greedy
  • If items have dependencies (precedence constraints) → use topological sorting + DP
  • If problem is about counting rather than optimization → use combinatorial DP

The core insight that makes this pattern work: The key insight is that optimal solutions to knapsack problems exhibit optimal substructure. If we know the optimal solution for a smaller capacity or fewer items, we can build up to the full problem. This allows us to use bottom-up DP where dp[i][w] represents the maximum value achievable with first i items and capacity w, leading to recurrence relation: dp[i][w] = max(dp[i-1][w], dp[i-1][w-weight[i]] + value[i]).

This pattern works because it transforms a combinatorial explosion of choices into manageable subproblems, with each state building upon previously computed optimal solutions.

3. Approach Evolution

Interview communication script:

My first instinct is to think about this as a classic dynamic programming problem where we want to maximize value while staying within weight constraints. But let me think about this more carefully - if I try a brute force approach, I'd have to check all possible combinations of items, which would be exponential time. That's definitely not acceptable.

Let me think about how to optimize this. I notice that if I maintain the invariant that dp[i][w] represents the maximum value achievable using only items from index 0 to i with weight capacity w, I can build up solutions incrementally. This is the key insight - instead of recomputing everything from scratch, I can use previously computed results.

I notice that for each item, I have two choices: either include it or exclude it. If I include it, the maximum value becomes the value of that item plus the best solution for remaining capacity with previous items. If I exclude it, the maximum value stays the same as the best solution without that item.

This suggests a DP approach where I can optimize space complexity too. The key optimization is to realize that for each item, I only need the previous row's values to compute the current row. This means I can reduce space from O(nW) to O(W) where W is the capacity.

My approach will be:

  1. Start with a 1D DP array initialized to zeros
  2. For each item, iterate backwards through capacities to avoid overwriting values I still need
  3. For each capacity w, update dp[w] = max(dp[w], dp[w-weight[i]] + value[i])
  4. The final answer is dp[capacity]

This gives us O(nW) time and O(W) space complexity, which is optimal for the 0/1 knapsack problem.

Brute-force approach: The naive approach would be to generate all possible subsets of items and calculate their total weight and value, keeping track of the maximum value that doesn't exceed capacity. This is exponential O(2^n) time complexity because we have 2^n possible combinations, and for each combination we'd need to validate the weight constraint.

Improved approach: The key optimization is recognizing that subproblems overlap in the decision tree. For example, if we've already computed what's the maximum value achievable with capacity 10 and items 0,1,2, we don't want to recompute that when considering item 3. This leads to the dynamic programming approach where we build solutions bottom-up.

Final approach with step-by-step reasoning:

  1. We define dp[w] as the maximum value achievable with weight capacity w
  2. For each item i, we iterate backwards through capacities from capacity down to weight[i]
  3. For each capacity w, we decide whether including item i gives us a better value than not including it
  4. The recurrence relation is: dp[w] = max(dp[w], dp[w - weight[i]] + value[i])
  5. We iterate through all items to build up the optimal solution
  6. The invariant maintained is that dp[w] always represents the best value achievable with exactly w capacity

Important invariants:

  • dp[w] always represents the optimal solution for weight capacity w so far
  • When iterating backwards through capacities, we don't overwrite values we still need for current item's computation
  • The solution is optimal because it considers all possible combinations through the DP state transitions

4. Data Structure Choice

For the knapsack problem, the primary data structures are:

1. 2D Dynamic Programming Table (dp[i][w])

  • Why needed: This is the core of the classic knapsack solution, storing the maximum value achievable with first i items and weight limit w
  • Time/Spatial impact: O(nW) time and space complexity where n is items count and W is weight capacity
  • Key insight: Each cell represents a subproblem state that builds upon previous computations

2. 1D Array (dp[w]) - Space-Optimized Version

  • Why needed: For memory optimization when we only need the final result, not all intermediate states
  • Time impact: Same O(nW) time complexity but reduced to O(W) space
  • Implementation note: Requires careful ordering of updates to maintain correctness

3. Priority Queue (for bounded knapsack variants)

  • Why needed: In some variations like the bounded knapsack where items can be taken multiple times (but with limits), we might use a priority queue to efficiently track best combinations
  • Time impact: O(nW log n) in worst case for some bounded variants

4. Item Tracking Structure (Optional)

  • Why needed: When we need to reconstruct which items were selected, we might maintain a parent pointer or item list alongside the DP table
  • Space impact: O(nW) additional space for tracking

The standard approach uses a 2D array for clarity and correctness, with the option to optimize to 1D space when only the final value is required. The choice between these structures directly impacts both time and space complexity trade-offs while maintaining the fundamental algorithmic correctness.

5. Algorithm Walkthrough

Let's trace through the classic 0/1 Knapsack problem with a concrete example:

Example: weights = [2, 1, 3, 2], values = [4, 2, 7, 3], capacity = 5

Step-by-step execution:

  1. Initialization: Create DP table dp[4][6] where dp[i][w] represents max value using first i items with weight capacity w. All values initialized to 0.

  2. Processing item 1 (weight=2, value=4):

    • For capacity 0-1: Can't include item → dp[1][w] = 0
    • For capacity 2-5: Can include item → dp[1][w] = max(0, 4) = 4
    • Result: dp[1][2..5] = [0, 0, 4, 4]
  3. Processing item 2 (weight=1, value=2):

    • For capacity 0-2: Can't include item → dp[2][w] = dp[1][w]
    • For capacity 3-5: Can include item → dp[2][w] = max(dp[1][w], dp[1][w-1] + 2)
    • Result: dp[2][3..5] = [0, 0, 4, 6, 6]
  4. Processing item 3 (weight=3, value=7):

    • For capacity 0-2: Can't include item → dp[3][w] = dp[2][w]
    • For capacity 3-5: Can include item → dp[3][w] = max(dp[2][w], dp[2][w-3] + 7)
    • Result: dp[3][5] = max(6, 4+7) = 11
  5. Processing item 4 (weight=2, value=3):

    • For capacity 0-1: Can't include item → dp[4][w] = dp[3][w]
    • For capacity 2-5: Can include item → dp[4][w] = max(dp[3][w], dp[3][w-2] + 3)
    • Result: dp[4][5] = max(11, 6+3) = 11

Final result: Maximum value is 11, achieved by selecting items with weights [2,3] and values [4,7].

Edge case handling:

  • Empty capacity returns 0
  • Items with weight > capacity are skipped
  • When items can't be included, previous best values are preserved

The algorithm terminates correctly because each cell represents an optimal subproblem solution that builds upon previous computations, ensuring global optimality.

6. Java Solution

public class KnapsackSolution {
    /**
     * Solves 0/1 Knapsack problem using dynamic programming with space optimization.
     * Time Complexity: O(n * W) where n is items count and W is knapsack capacity
     * Space Complexity: O(W) - optimized space version
     */
    public int knapsack(int[] weights, int[] values, int capacity) {
        // Handle edge cases
        if (weights == null || values == null || weights.length == 0 || capacity <= 0) {
            return 0;
        }
        
        int n = weights.length;
        // Use only one array since we only need previous row values
        int[] dp = new int[capacity + 1];
        
        // Process each item
        for (int i = 0; i < n; i++) {
            // Traverse backwards to avoid using updated values in same iteration
            for (int w = capacity; w >= weights[i]; w--) {
                // Either include current item or exclude it
                dp[w] = Math.max(dp[w], dp[w - weights[i]] + values[i]);
            }
        }
        
        return dp[capacity];
    }
    
    /**
     * Returns the actual items selected for optimal knapsack solution
     * This version maintains item tracking for reconstruction
     */
    public int knapsackWithItems(int[] weights, int[] values, int capacity) {
        if (weights == null || values == null || weights.length == 0 || capacity <= 0) {
            return 0;
        }
        
        int n = weights.length;
        int[][] dp = new int[n + 1][capacity + 1];
        
        // Fill DP table
        for (int i = 1; i <= n; i++) {
            for (int w = 0; w <= capacity; w++) {
                // Don't take the item
                dp[i][w] = dp[i - 1][w];
                
                // Take the item if it fits
                if (weights[i - 1] <= w) {
                    dp[i][w] = Math.max(dp[i][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]);
                }
            }
        }
        
        // Backtrack to find selected items (optional - only if needed)
        // For this implementation, we just return the maximum value
        return dp[n][capacity];
    }
}

7. Complexity Analysis

Time Complexity: O(n × W) where n is the number of items and W is the knapsack capacity.

The dynamic programming solution uses a 2D table dp[i][w] where:

  • i ranges from 0 to n (number of items)
  • w ranges from 0 to W (knapsack capacity)

Each cell computation takes O(1) time, and we compute n×W cells total.

Space Complexity: O(n × W) for the 2D DP table.

This can be optimized to O(W) space by using only two 1D arrays (current and previous rows), but the fundamental time complexity remains O(n × W) as we must consider all combinations of items and weights.

Why these bounds are correct:

  • We process each item exactly once
  • For each item, we consider all possible weights up to capacity W
  • The recurrence relation dp[i][w] = max(dp[i-1][w], dp[i-1][w-weight[i]] + value[i]) is computed once per cell
  • The solution explores the entire search space of valid combinations

Optimality: This is optimal for the 0/1 knapsack problem when the capacity W is polynomial in n. The problem is NP-hard, but this dynamic programming approach provides pseudo-polynomial time complexity which is considered optimal for this variant. For truly optimal solutions, we'd need exponential time, but this O(n×W) approach represents the best practical trade-off between correctness and efficiency.

The complexity is near-optimal because any algorithm solving this problem must consider all combinations of items and weights up to capacity W, making O(n×W) the theoretical lower bound for exact solutions.

8. Edge Cases & Pitfalls

Empty and Minimal Inputs

  • Empty input array: When weights or values is empty, the knapsack capacity should be checked first. If capacity is 0, return 0; otherwise, the problem has no meaningful solution.
  • Single item: When there's only one item, the solution reduces to checking if that item fits in the knapsack and taking it if possible.
  • Zero capacity: If capacity = 0, the maximum value is always 0 regardless of items.

Duplicate Values and Repeated States

  • Duplicate weights/values: The algorithm must handle cases where multiple items have the same weight or value. These are valid and should be considered in the dynamic programming state.
  • Same weight/value combinations: When multiple items have identical weight and value, the DP approach still works correctly, but care must be taken to ensure that all combinations are considered.

Boundary Conditions

  • Capacity overflow: If capacity is extremely large, it may cause integer overflow in intermediate calculations. Using long types for capacity and intermediate sums can prevent this.
  • Large weights/values: Very large values may cause overflow in the DP table. Consider using long or modular arithmetic if needed.
  • Negative weights/values: If negative weights or values are allowed, the problem becomes more complex and requires a different approach than standard DP.

Common Implementation Mistakes

  • Incorrect initialization: Forgetting to initialize the DP table properly (e.g., setting all values to 0 instead of -1 or using wrong base cases) can lead to incorrect results.
  • Off-by-one errors: Misaligning indices when iterating through items or capacities can cause incorrect state transitions. For example, using i <= n instead of i < n or starting from 1 instead of 0.
  • Incorrect recurrence relation: Writing dp[i][w] = max(dp[i-1][w], dp[i-1][w-weight[i]] + value[i]) without ensuring that w >= weight[i] can lead to incorrect results or runtime errors.
  • Not handling zero capacity: If the knapsack has zero capacity, any item with positive weight should not be included, but this must be handled explicitly.
  • Assuming items are sorted: The solution assumes that items can be processed in any order. If the problem requires specific ordering (e.g., sorted by weight), that must be enforced.

Additional Considerations

  • Memory constraints: For very large capacities, the O(n × capacity) space complexity can be a bottleneck. In such cases, consider using space-optimized approaches or alternative algorithms like branch and bound.
  • Integer overflow: When computing weight[i] + value[i], if the values are large, intermediate sums might overflow. Using long or checking for overflow conditions can help.
  • Unbounded knapsack variant: If the problem allows unlimited use of items (unbounded knapsack), a different recurrence relation is needed (dp[w] = max(dp[w], dp[w - weight[i]] + value[i])), and the solution must be adapted accordingly.

These edge cases highlight the importance of careful input validation, proper initialization, and handling of boundary conditions in a robust implementation.

9. Alternative Approaches

There are several alternative approaches to solving knapsack-family problems, each with different trade-offs:

1. Brute Force with Bit Manipulation: For small input sizes (n ≤ 20), we can generate all 2^n possible combinations using bit manipulation. Each bit represents whether to include an item. This approach is O(2^n) time and O(1) space but only practical for very small inputs.

2. Recursive with Memoization: Instead of bottom-up DP, we can use top-down recursion with memoization. The recursive relation is dp[i][w] = max(dp[i-1][w], dp[i-1][w-weight[i]] + value[i]). This has the same complexity as DP but with function call overhead and potential stack overflow for large inputs.

3. Space-Optimized 1D DP: Since we only need the previous row to compute current row, we can reduce space from O(nW) to O(W). This approach iterates backwards through weights to avoid overwriting values we still need.

4. Fractional Knapsack Greedy: For the fractional knapsack variant where items can be broken into parts, we can use a greedy approach by sorting items by value-to-weight ratio and taking as much as possible of each item in descending order. This is O(n log n) time but only works for fractional knapsack, not the 0/1 variant.

5. Branch and Bound: For optimization, we can use branch and bound with pruning to explore the solution space more intelligently. This can be faster than DP in some cases but is more complex to implement and has no guaranteed time bounds.

The chosen solution (bottom-up 2D DP) is preferred because it's intuitive, handles all edge cases cleanly, and provides optimal time complexity for the 0/1 knapsack problem. The alternatives are useful in specific constrained scenarios but don't offer the same balance of simplicity and efficiency for general use.

10. Test Cases

public class KnapsackTestCases {
    public static void main(String[] args) {
        // Test case 1: Basic example from problem description
        int[] weights = {2, 1, 3, 2};
        int[] values = {2, 4, 6, 3};
        int capacity = 5;
        // Expected: 10 (items with weights 2,3 and values 4,6)
        
        // Test case 2: Empty input
        int[] weights2 = {};
        int[] values2 = {};
        int capacity2 = 5;
        // Expected: 0
        
        // Test case 3: All items exceed capacity
        int[] weights3 = {6, 7, 8};
        int[] values3 = {1, 2, 3};
        int capacity3 = 5;
        // Expected: 0
        
        // Test case 4: Single item fits
        int[] weights4 = {3};
        int[] values4 = {5};
        int capacity4 = 5;
        // Expected: 5
        
        // Test case 5: Items with zero weight (edge case)
        int[] weights5 = {0, 1, 2};
        int[] values5 = {3, 4, 5};
        int capacity5 = 3;
        // Expected: 12 (all items)
        
        // Test case 6: Duplicate weights/values
        int[] weights6 = {2, 2, 3};
        int[] values6 = {4, 4, 5};
        int capacity6 = 5;
        // Expected: 9 (items with weights 2,3 and values 4,5)
    }
}

Sample test cases include:

  1. Basic functionality: Items with weights [2,1,3,2] and values [2,4,6,3] with capacity 5 should return 10
  2. Edge case - empty: Empty arrays should return 0
  3. Edge case - no valid items: All items exceed capacity
  4. Edge case - single item: One item that fits entirely
  5. Edge case - zero weight: Items with zero weight should be considered
  6. Edge case - duplicates: Items with same weights/values

The test cases cover typical scenarios and edge conditions that would reveal implementation bugs or incorrect handling of boundary conditions in a knapsack solution.

11. Final Summary

The core idea is to solve the 0/1 knapsack problem optimally using dynamic programming with space optimization, where each item can be either included or excluded to maximize value within the weight constraint. This solution works by maintaining only the previous row of the DP table, reducing space complexity from O(nW) to O(W), and efficiently computes the maximum value achievable for each possible weight capacity up to the knapsack's limit. The approach is optimal for the given constraints, providing a clean balance between time efficiency (O(nW)) and space efficiency (O(W)), making it suitable for large-scale applications where memory usage is critical.

Was this article helpful?

Topics in this article

More from DSA Patterns

Stay in the Loop

Get curated DSA patterns, coding problems, frontend and backend LLD/HLD, and AI/ML System Design insights delivered straight to your inbox. No spam, just focused interview and engineering content.