Skip to content

Commit 91bb99f

Browse files
committed
CompleteKnapsack
1 parent 9d2999a commit 91bb99f

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Diff for: src/knapsack/CompleteKnapsack.java

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/**
2+
* There are N objects and a bag with capacity of V. Evey type of object can be
3+
* used with unlimited number of times.
4+
* The ith object is having costs[i] and weights[i].
5+
* Find out which objects can be put into the bag in order to have maximum value.
6+
*/
7+
8+
9+
public class CompleteKnapsack {
10+
11+
/**
12+
* dp[i][v] = max{dp[i-1][v], dp[i][v-c[i]] + w[i]}
13+
*/
14+
public int maxValue(int[] costs, int[] weights, int V) {
15+
if (costs == null || weights == null) return 0;
16+
int N = costs.length;
17+
int[][] dp = new int[N + 1][V + 1];
18+
19+
for (int i=1; i<=N; i++) {
20+
for (int v=1; v<=V; v++) {
21+
if (v < costs[i-1]) {
22+
dp[i][v] = dp[i-1][v];
23+
} else {
24+
dp[i][v] = Math.max(dp[i-1][v], dp[i][v - costs[i-1]] + weights[i-1]);
25+
}
26+
}
27+
}
28+
return dp[N][V];
29+
}
30+
31+
32+
/**
33+
* dp[v] = max{dp[v], dp[v-c[i]] + w[i]}
34+
*/
35+
public int maxValue2(int[] costs, int[] weights, int V) {
36+
if (costs == null || weights == null) return 0;
37+
int N = costs.length;
38+
int[] dp = new int[V + 1];
39+
40+
for (int i=0; i<N; i++) {
41+
for (int v=costs[i]; v<=V; v++) {
42+
dp[v] = Math.max(dp[v], dp[v - costs[i]] + weights[i]);
43+
}
44+
}
45+
return dp[V];
46+
}
47+
48+
49+
public static void main(String[] args) {
50+
CompleteKnapsack slt = new CompleteKnapsack();
51+
52+
int[] costs = new int[]{};
53+
int[] weights = new int[]{};
54+
System.out.println(slt.maxValue(costs, weights, 10));
55+
System.out.println(slt.maxValue2(costs, weights, 10));
56+
57+
costs = new int[]{2};
58+
weights = new int[]{2};
59+
System.out.println(slt.maxValue(costs, weights, 2));
60+
System.out.println(slt.maxValue2(costs, weights, 2));
61+
62+
costs = new int[]{2};
63+
weights = new int[]{2};
64+
System.out.println(slt.maxValue(costs, weights, 3));
65+
System.out.println(slt.maxValue2(costs, weights, 3));
66+
67+
costs = new int[]{2};
68+
weights = new int[]{2};
69+
System.out.println(slt.maxValue(costs, weights, 1));
70+
System.out.println(slt.maxValue2(costs, weights, 1));
71+
72+
73+
74+
75+
76+
}
77+
78+
79+
// procedure CompletePack(cost,weight)
80+
// for v=cost..V
81+
// f[v]=max{f[v],f[v-c[i]]+w[i]}
82+
83+
}

0 commit comments

Comments
 (0)