-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0-1 Knapsack Problem.java
More file actions
95 lines (72 loc) · 2.96 KB
/
0-1 Knapsack Problem.java
File metadata and controls
95 lines (72 loc) · 2.96 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
public class MyClass {
public int solveKnapsack(int[] profits, int[] weights, int capacity) {
// TODO: Write your code here
int n = profits.length;
int[][] dp = new int[n][capacity + 1];
//return helper(profits, weights, 0, profits.length, capacity);
//return helperTopDownDp(profits, weights, 0, n, capacity, dp);
return bottomUpDp(profits, weights, n, capacity);
}
int bottomUpDp(int[] profits, int[] weights, int n, int capacity) {
int result = 0;
int[][] dp = new int[n][capacity + 1];
for (int i = 0; i < n; i++)
dp[i][0] = 0;
// if we have only one weight, we will take it if it is not more than the capacity
for (int c = 0; c <= capacity; c++) {
if (weights[0] <= c)
dp[0][c] = profits[0];
}
for (int i = 1; i < n; i++) {
for (int j = 1; j <= capacity; j++) {
if (weights[i] <= j) {
dp[i][j] = Math.max(profits[i] + dp[i - 1][j - weights[i]], dp[i][j]);
}
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j]);
}
}
return dp[n - 1][capacity];
}
int helperTopDownDp(int[] profits, int[] weights, int index, int n, int capacity, int[][] dp) {
if (index == n || capacity <= 0 || weights[index] > capacity) {
return 0;
}
if (dp[index][capacity] == 0) {
int profitIncludingItem = profits[index] + helperTopDownDp(profits, weights, index + 1, n, capacity - weights[index], dp);
int profitExcludingItem = helperTopDownDp(profits, weights, index + 1, n, capacity, dp);
dp[index][capacity] = Math.max(profitIncludingItem, profitExcludingItem);
}
return dp[index][capacity];
}
int helper(int[] profits, int[] weights, int index, int n, int capacity) {
if (index == n || capacity <= 0 || weights[index] > capacity) {
return 0;
}
return Math.max(
profits[index] + helper(profits, weights, index + 1, n, capacity - weights[index]),
helper(profits, weights, index + 1, n, capacity));
}
public static void main(String[] args) {
MyClass ks = new MyClass();
int[] profits = {
1,
6,
10,
16
};
int[] weights = {
1,
2,
3,
5
};
int maxProfit = ks.solveKnapsack(profits, weights, 7);
System.out.println("Total knapsack profit ---> " + maxProfit);
maxProfit = ks.solveKnapsack(profits, weights, 6);
System.out.println("Total knapsack profit ---> " + maxProfit);
maxProfit = ks.solveKnapsack(profits, weights, 5);
System.out.println("Total knapsack profit ---> " + maxProfit);
maxProfit = ks.solveKnapsack(profits, weights, 1);
System.out.println("Total knapsack profit ---> " + maxProfit);
}
}