Method
knapSack
(int W, int wt[], int val[], int n)
Source from the content-addressed store, hash-verified
| 8 | } |
| 9 | |
| 10 | public int knapSack(int W, int wt[], int val[], int n) |
| 11 | { |
| 12 | int i, w; |
| 13 | int[][] K = new int[n+1][W+1]; |
| 14 | for(i=0; i<=n; i++) |
| 15 | { |
| 16 | for(w=0; w<=W; w++) |
| 17 | { |
| 18 | if(i == 0 || w == 0) |
| 19 | { |
| 20 | K[i][w] = 0; |
| 21 | } |
| 22 | else if(wt[i-1] <= w) |
| 23 | { |
| 24 | K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); |
| 25 | } |
| 26 | else |
| 27 | { |
| 28 | K[i][w] = K[i-1][w]; |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | return K[n][W]; |
| 33 | } |
| 34 | |
| 35 | public static void main(String[] args) |
| 36 | { |
Tested by
no test coverage detected