80. 0/1 Knapsack

MediumDynamic Programming (2-D)Classic problem (GeeksforGeeks style)

Item i has weight weights[i] and value values[i]. Each item can be taken at most once. Return the maximum total value that fits in a bag of the given capacity. This classic problem is the basis of many interview questions (subset sum, partition, target sum).

Example 1

Input: weights = [1,3,4,5], values = [1,4,5,7], capacity = 7
Output: 9
Explanation: Take the items of weight 3 and 4: value 4 + 5 = 9.

Example 2

Input: weights = [5,4,6,3], values = [10,40,30,50], capacity = 10
Output: 90
Explanation: Weights 4 + 3: value 40 + 50.
Hint 1

dp[i][c] = max(skip item i, take item i if it fits).

Hint 2

With a 1-D array, loop capacity downwards so an item is not reused.

Dynamic ProgrammingKnapsack