DevPath

← All problems

0/1 Knapsack

Medium dynamic-programming

Description

Given item weights and values and a capacity, return the maximum value of items you can carry, each used at most once.

Constraints

1 <= items <= 1000; 0 <= capacity <= 2000

Examples

Input: weights = [1,2,3], values = [6,10,12], capacity = 5

Output: 22

Hints (1)
  • Iterate items and capacity; going backwards avoids reusing an item.

Solutions

1D DP descending capacity. · Time O(n*capacity) · Space O(capacity)

func knapsack(weights, values []int, capacity int) int {
    dp := make([]int, capacity+1)
    for i, w := range weights {
        for c := capacity; c >= w; c-- {
            if v := dp[c-w] + values[i]; v > dp[c] {
                dp[c] = v
            }
        }
    }
    return dp[capacity]
}

Create a free account to submit solutions, track progress and save problems.

Create account