Created
September 6, 2021 08:35
-
-
Save akshat-fsociety/0a2fa8c096ff15457ce2a57f37519dfe 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 unboundedKnapsack{ | |
static int knapSack(int n, int W, int val[], int wt[]) | |
{ | |
// 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][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