Advertisement
vaibhav1906

Knapsack DP

Dec 1st, 2021
640
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.56 KB | None | 0 0
  1. class Solution
  2. {
  3.     public:
  4.     //Function to return max value that can be put in knapsack of capacity W.
  5.     int knapSack(int W, int wt[], int val[], int n)
  6.     {
  7.        // Your code here
  8.        vector<vector<int>> dp(n+1,vector<int>(W+1,0));
  9.        for(int i=1;i<=n;i++)
  10.        {
  11.            for(int j=1;j<=W;j++)
  12.            {
  13.                 if(wt[i-1]>j)
  14.                     dp[i][j]=dp[i-1][j];
  15.                 else
  16.                     dp[i][j]=max(dp[i-1][j],val[i-1]+dp[i-1][j-wt[i-1]]);
  17.            }
  18.        }
  19.        return dp[n][W];
  20.     }
  21. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement