13. 0-1 Knapsack Problem
The problem can be found at the following link: Question Link
Problem Description
Given n items, each with a weight and value, and a knapsack with a capacity of W, the task is to determine the maximum total value that can be obtained by placing items in the knapsack without exceeding its weight capacity.
🔹 Note:
Each item can be either included or excluded (hence, 0-1 Knapsack).
Each item is available only once.
Examples
Example 1:
Input:
W = 4
val[] = [1, 2, 3]
wt[] = [4, 5, 1]Output:
3Explanation:
Choose the last item (value = 3, weight = 1), as it fits within the weight limit and maximizes the value.
Example 2:
Input:
Output:
Explanation:
No item fits within the weight limit W = 3, so the maximum value obtained is 0.
Example 3:
Input:
Output:
Explanation:
Select the third item (value = 30, weight = 2).
Select the fourth item (value = 50, weight = 3).
Total weight = 2 + 3 = 5 (within limit).
Total value = 30 + 50 = 80.
Constraints:
$2 \leq \text{val.size()} = \text{wt.size()} \leq 10^3$
$1 \leq W \leq 10^3$
$1 \leq \text{val}[i] \leq 10^3$
$1 \leq \text{wt}[i] \leq 10^3$
My Approach:
Optimized Space Dynamic Programming
Algorithm Steps:
Use a 1D DP array (
dp[W+1]) to track the maximum value at each capacity from0toW.Iterate over each item and update the DP array backwards (from
Wtowt[i]), ensuring each item is used only once.For each weight
j, decide whether to:Include the current item:
dp[j] = max(dp[j], val[i] + dp[j - wt[i]]).Exclude the current item (keep previous value).
Return
dp[W], which contains the maximum value achievable with capacityW.
Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N * W), as we processNitems and iterate overWcapacities.Expected Auxiliary Space Complexity:
O(W), as we use a 1D DP array of sizeW+1.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated