|
| 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(); // Number of items |
| 6 | + |
| 7 | + // DP table to store the maximum value for each subproblem (capacity, number of items) |
| 8 | + // dp[i][w] will store the maximum value with the first i items and a knapsack capacity of w |
| 9 | + vector<vector<int>> dp(n, vector<int>(capacity + 1, 0)); |
| 10 | + |
| 11 | + // Initialize the first row of the DP table (only for the first item) |
| 12 | + // We fill the DP table by checking if the current item can be included in the knapsack |
| 13 | + for(int w = weight[0]; w <= capacity; w++){ |
| 14 | + dp[0][w] = (weight[0] <= w) ? value[0] : 0; // If the first item's weight is less than or equal to the capacity, include its value |
| 15 | + } |
| 16 | + |
| 17 | + // Fill the rest of the DP table for all the other items (i > 0) |
| 18 | + for(int i = 1; i < n; i++){ |
| 19 | + for(int w = 0; w <= capacity; w++){ |
| 20 | + |
| 21 | + // Case 1: Including the current item (i) |
| 22 | + int include = 0; |
| 23 | + if(weight[i] <= w) { // If the current item can fit in the knapsack |
| 24 | + include = value[i] + dp[i-1][w - weight[i]]; // Add its value and reduce the capacity accordingly |
| 25 | + } |
| 26 | + |
| 27 | + // Case 2: Excluding the current item (i) |
| 28 | + int exclude = dp[i-1][w]; // Simply carry forward the value from the previous row, without including the item |
| 29 | + |
| 30 | + // Store the maximum value of including or excluding the current item |
| 31 | + dp[i][w] = max(include, exclude); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + // The answer will be in dp[n-1][capacity], which contains the maximum value with all items and the given capacity |
| 36 | + return dp[n - 1][capacity]; |
| 37 | + } |
| 38 | + |
| 39 | + // Wrapper function that calls the solve function |
| 40 | + int knapSack(int capacity, vector<int> &val, vector<int> &wt) { |
| 41 | + return solve(capacity, val, wt); // Return the result from the solve function |
| 42 | + } |
| 43 | +}; |
0 commit comments