Created
August 30, 2021 07:54
-
-
Save akshat-fsociety/a63c5e8ba7682dcf9d43ef5daf6fa565 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution | |
{ | |
static int knapSack(int W, int wt[], int val[], int n) | |
{ | |
// Initialize the matrix with 0's | |
int dp[][] = new int[n+1][W+1]; | |
for(int i=0; i<n+1; i++){ | |
for(int j=0; j<W+1; j++){ | |
if(i==0 || j==0) | |
dp[i][j] = 0; | |
} | |
} | |
// Processing and calculating the values | |
for(int i=1; i<n+1; i++){ | |
for(int j=1; j<W+1; j++){ | |
if(wt[i-1]<=j) | |
dp[i][j] = Math.max(val[i-1]+dp[i-1][j-wt[i-1]],dp[i-1][j]); | |
else | |
dp[i][j] = dp[i-1][j]; | |
} | |
} | |
return dp[n][W]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment