π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:
3
Explanation:
Choose the last item (value = 3, weight = 1), as it fits within the weight limit and maximizes the value.
Example 2:
Input:
W = 3
val[] = [1, 2, 3]
wt[] = [4, 5, 6]
Output:
0
Explanation:
No item fits within the weight limit W = 3, so the maximum value obtained is 0.
Example 3:
Input:
W = 5
val[] = [10, 40, 30, 50]
wt[] = [5, 4, 2, 3]
Output:
80
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 from0
toW
.Iterate over each item and update the DP array backwards (from
W
towt[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 processN
items and iterate overW
capacities.Expected Auxiliary Space Complexity:
O(W)
, as we use a 1D DP array of sizeW+1
.
π Solution Code
Code (C++)
class Solution {
public:
int knapsack(int W, vector<int> &val, vector<int> &wt) {
vector<int> dp(W + 1);
for (int i = 0; i < wt.size(); i++)
for (int j = W; j >= wt[i]; j--)
dp[j] = max(dp[j], val[i] + dp[j - wt[i]]);
return dp[W];
}
};
Code (Java)
class Solution {
static int knapsack(int W, int[] val, int[] wt) {
int[] dp = new int[W + 1];
for (int i = 0; i < wt.length; i++)
for (int j = W; j >= wt[i]; j--)
dp[j] = Math.max(dp[j], val[i] + dp[j - wt[i]]);
return dp[W];
}
}
Code (Python)
class Solution:
def knapsack(self, W, val, wt):
dp = [0] * (W + 1)
for i in range(len(wt)):
for j in range(W, wt[i] - 1, -1):
dp[j] = max(dp[j], val[i] + dp[j - wt[i]])
return dp[W]
π― 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