Skip to content

Commit 8e35b57

Browse files
authored
Create 04 - Space Optimization - 2 | DP | Approach.cpp
1 parent d50c03c commit 8e35b57

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution {
2+
public:
3+
// Function to solve the 0/1 Knapsack problem using dynamic programming
4+
int solve(int capacity, vector<int> &value, vector<int> &weight){
5+
int n = weight.size(); // Get the number of items
6+
7+
// Create a 1D array `curr[]` to store the maximum value for each weight capacity from 0 to the given capacity.
8+
// It will store the result of the current item.
9+
vector<int> curr(capacity + 1, 0);
10+
11+
// Initialize the first row of the DP table for the first item.
12+
// If the weight of the first item is less than or equal to the current capacity,
13+
// we store its value in the `curr[]` array (otherwise 0).
14+
for(int w = 0; w <= capacity; w++) {
15+
curr[w] = (weight[0] <= w) ? value[0] : 0; // If the first item's weight <= w, include its value
16+
}
17+
18+
// Process the remaining items (i from 1 to n-1)
19+
for(int i = 1; i < n; i++){
20+
// For each capacity from the given weight to 0 (iterating backwards)
21+
// This prevents overwriting results of the current item during the same iteration
22+
for(int w = capacity; w >= 0; w--){
23+
24+
// Case 1: Including the current item (i)
25+
int include = 0;
26+
if(weight[i] <= w) { // Check if the current item's weight can fit in the knapsack
27+
include = value[i] + curr[w - weight[i]]; // Add the value of the current item and reduce the capacity
28+
}
29+
30+
// Case 2: Excluding the current item (i)
31+
int exclude = curr[w]; // Simply carry forward the value from the previous item (same weight)
32+
33+
// Store the maximum value of including or excluding the current item
34+
curr[w] = max(include, exclude); // The optimal solution for this capacity is the best of both cases
35+
}
36+
}
37+
38+
// The final answer is in `curr[capacity]`, which contains the maximum value achievable with the given capacity
39+
return curr[capacity];
40+
}
41+
42+
// Wrapper function that calls the solve function with the given capacity, values, and weights
43+
int knapSack(int capacity, vector<int> &val, vector<int> &wt) {
44+
return solve(capacity, val, wt); // Return the result from the solve function
45+
}
46+
};

0 commit comments

Comments
 (0)