Knapsack Problem - Problem
You are given a knapsack with a maximum weight capacity and a collection of items, each with a specific weight and value. Your goal is to determine the maximum value you can achieve by selecting items to put in the knapsack without exceeding the weight capacity.
This is the classic 0/1 Knapsack Problem where each item can either be included (1) or excluded (0) - you cannot take partial items or multiple copies of the same item.
Input:
weights: An array of positive integers representing the weight of each itemvalues: An array of positive integers representing the value of each itemcapacity: A positive integer representing the maximum weight capacity of the knapsack
Output:
Return the maximum value that can be obtained.
Input & Output
Example 1 — Basic Case
$
Input:
weights = [2,1,3], values = [60,40,120], capacity = 5
›
Output:
160
💡 Note:
Select items 1 and 2: weight = 1+3 = 4 ≤ 5, value = 40+120 = 160. This is optimal.
Example 2 — Single Item
$
Input:
weights = [10], values = [60], capacity = 15
›
Output:
60
💡 Note:
Only one item available and it fits in the knapsack, so take it for value 60.
Example 3 — No Items Fit
$
Input:
weights = [5,4,6], values = [10,40,30], capacity = 3
›
Output:
0
💡 Note:
All items are too heavy for the capacity of 3, so maximum value is 0.
Constraints
- 1 ≤ weights.length ≤ 100
- weights.length == values.length
- 1 ≤ weights[i], values[i] ≤ 1000
- 1 ≤ capacity ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code