πDay 10. 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.
π Example Walkthrough:
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.
π Solution Code
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