forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsackProblem.java
More file actions
44 lines (31 loc) · 823 Bytes
/
KnapsackProblem.java
File metadata and controls
44 lines (31 loc) · 823 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Created by vampire-slayer on 29/10/16.
* Java solution to the Knapsack problem using dynamic programming
*/
public class KnapsackProblem {
public static int knapsack(int w, int[] weights, int[] values, int n) {
int i, j;
int[][] DP = new int[n + 1][w + 1];
for (i = 0; i <= n; i++) {
for (j = 0; j <= w; j++) {
if (i == 0 || j == 0)
DP[i][j] = 0;
else if (weights[i - 1] <= j)
DP[i][j] = Math.max(values[i - 1] + DP[i - 1][j - weights[i - 1]], DP[i - 1][j]);
else
DP[i][j] = DP[i - 1][j];
}
}
return DP[n][w];
}
public static void main (String[] args) {
int[] values = {11, 22, 33, 44, 55};
int[] weights = {111, 121, 131, 141, 151};
int w = 300;
int n = weights.length;
System.out.println(knapsack(w, weights, values, n));
}
}
/* Output
99
*/