Method
knapSack_01_Rec
(int[] weight, int[] value, int cap, int n, int[][] dp)
Source from the content-addressed store, hash-verified
| 27 | } |
| 28 | } |
| 29 | public static int knapSack_01_Rec(int[] weight, int[] value, int cap, int n, int[][] dp){ |
| 30 | int N = n; |
| 31 | int Cap = cap; |
| 32 | for(n = 0;n<=N;n++){ |
| 33 | for(cap = 0;cap<=Cap;cap++){ |
| 34 | if(cap == 0 || n == 0){ |
| 35 | dp[n][cap] =0; |
| 36 | continue; |
| 37 | } |
| 38 | |
| 39 | int maxProfit = 0; |
| 40 | if(cap-weight[n-1]>=0){ |
| 41 | maxProfit = Math.max(maxProfit,dp[n-1][cap-weight[n-1]]+value[n-1]); |
| 42 | } |
| 43 | maxProfit = Math.max(maxProfit, dp[n-1][cap]); |
| 44 | dp[n][cap] = maxProfit; |
| 45 | } |
| 46 | } |
| 47 | return dp[N][Cap]; |
| 48 | } |
| 49 | } |
Tested by
no test coverage detected