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 item
  • values: An array of positive integers representing the value of each item
  • capacity: 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
0/1 Knapsack ProblemINPUTItems:Weight: 2Value: 60Weight: 1Value: 40Weight: 3Value: 120Knapsack Capacity: 5Max Weight: 5Goal: Select items to maximizevalue while staying within weight limitALGORITHM STEPS1Create 2D DP table (items × capacity)2For each item and weight:dp[i][w] = max(exclude, include)3Include if: weight[i] ≤ wvalue[i] + dp[i-1][w-weight[i]]4Final answer at dp[n][capacity]DP Table Preview:dp[1][5] = 60, dp[2][5] = 100dp[3][5] = 160 ← Maximum!FINAL RESULTMaximum Value160Selected Items:Item 1w=1, v=40Item 2w=3, v=120Total Weight: 1 + 3 = 4 ≤ 5 ✓Total Value: 40 + 120 = 160Key Insight:Dynamic programming breaks the problem into subproblems: "What's the maximum value using the first i items with capacity w?" By building solutions from smaller to larger subproblems, we avoid the exponential time of trying all combinations.TutorialsPoint - 0/1 Knapsack Problem | 2D Dynamic Programming
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
78.0K Views
High Frequency
~25 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen