0/1 Knapsack Problem
Definition
You have a bag (Knapsack) with a weight limit $W$. You have a list of items, each with a weight and a value. You want to maximize the total value in the bag without exceeding the weight limit. You cannot break items (0/1 property: either take it or leave it).
How it Works
For every item, you have a choice:
- Include it: Add its value to the total, subtract its weight from capacity.
- Exclude it: Skip it and keep the capacity the same.
- Result: max(Include, Exclude).
Code Example (Java)
def knapSack(W, wt, val, n): dp = [[0 for x in range(W + 1)] for x in range(n + 1)] # Build table dp[][] in bottom up manner for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: dp[i][w] = 0 elif wt[i-1] <= w: # Max of (including item, excluding item) dp[i][w] = max(val[i-1] + dp[i-1][w-wt[i-1]], dp[i-1][w]) else: dp[i][w] = dp[i-1][w] return dp[n][W] val = [60, 100, 120] wt = [10, 20, 30] W = 50 n = len(val) print(knapSack(W, wt, val, n)) # Output: 220
Complexity Analysis
- Time Complexity: O(N times W) where N is number of items and W is capacity.
- Space Complexity: O(N times W.
Use Cases
- Resource Allocation: Budgeting money for projects.
- Cargo Loading: Optimizing truck/ship loads.