|
| 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 | + // We only need two rows at a time (previous and current), so we create two 1D arrays: |
| 8 | + // prev[] will store the maximum values for the previous item, |
| 9 | + // curr[] will store the maximum values for the current item. |
| 10 | + vector<int> prev(capacity + 1, 0); |
| 11 | + vector<int> curr(capacity + 1, 0); |
| 12 | + |
| 13 | + // Initialize the first row of the DP table for the first item. |
| 14 | + // If the weight of the first item is less than or equal to the current capacity, |
| 15 | + // we store its value in the prev[] array (otherwise 0). |
| 16 | + for(int w = 0; w <= capacity; w++) { |
| 17 | + prev[w] = (weight[0] <= w) ? value[0] : 0; // If the first item's weight <= w, include its value |
| 18 | + } |
| 19 | + |
| 20 | + // Process the remaining items (i from 1 to n-1) |
| 21 | + for(int i = 1; i < n; i++){ |
| 22 | + // For each capacity from 0 to the given capacity |
| 23 | + for(int w = 0; w <= capacity; w++){ |
| 24 | + |
| 25 | + // Case 1: Including the current item (i) |
| 26 | + int include = 0; |
| 27 | + if(weight[i] <= w) { // Check if the current item's weight can fit in the knapsack |
| 28 | + include = value[i] + prev[w - weight[i]]; // Add the value of the current item and reduce the capacity |
| 29 | + } |
| 30 | + |
| 31 | + // Case 2: Excluding the current item (i) |
| 32 | + int exclude = prev[w]; // Simply carry forward the value from the previous row without including the item |
| 33 | + |
| 34 | + // Store the maximum value of including or excluding the current item |
| 35 | + curr[w] = max(include, exclude); |
| 36 | + } |
| 37 | + |
| 38 | + // After processing the current item, move curr[] to prev[] to use it in the next iteration |
| 39 | + prev = curr; |
| 40 | + } |
| 41 | + |
| 42 | + // The answer will be in curr[capacity], which contains the maximum value with all items considered |
| 43 | + return curr[capacity]; |
| 44 | + } |
| 45 | + |
| 46 | + // Wrapper function that calls the solve function with the given capacity, values, and weights |
| 47 | + int knapSack(int capacity, vector<int> &val, vector<int> &wt) { |
| 48 | + return solve(capacity, val, wt); // Return the result from the solve function |
| 49 | + } |
| 50 | +}; |
0 commit comments