Skip to content

Commit 8e1fd8a

Browse files
committed
Freestyle | Knapsack Unbounded | Java
1 parent 2c15e53 commit 8e1fd8a

File tree

3 files changed

+67
-34
lines changed

3 files changed

+67
-34
lines changed

.idea/workspace.xml

Lines changed: 37 additions & 34 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

freestyle/src/main/java/com/devstromo/dp/knapsack/knapsack01/Solution.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,26 @@ public int[] knapsack01With1DArraySelected(int n, int m, int[] wt, int[] profits
5858
return selectedItems;
5959
}
6060

61+
public int knapsackUnbounded(int n, int m, int[] wt, int[] profits) {
62+
int[][] dp = new int[n][m + 1];
63+
for (int capacity = 0; capacity <= m; capacity++) {
64+
if (wt[0] <= capacity) {
65+
dp[0][capacity] = (capacity / wt[0]) * profits[0];
66+
}
67+
}
68+
for (int item = 1; item < n; item++) {
69+
for (int capacity = 1; capacity <= m; capacity++) {
70+
int includeProfit = 0;
71+
int excludeProfit = dp[item - 1][capacity];
72+
if (wt[item] <= capacity) {
73+
includeProfit = profits[item] + dp[item][capacity - wt[item]];
74+
}
75+
dp[item][capacity] = Math.max(includeProfit, excludeProfit);
76+
}
77+
}
78+
return dp[n - 1][m];
79+
}
80+
6181
private int[][] knapsack01DP(int n, int m, int[] wt, int[] profits) {
6282
int[][] dp = new int[n + 1][m + 1];
6383
int i, w;

freestyle/src/test/java/com/devstromo/dp/knapsack/knapsack01/SolutionUnitTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,4 +87,14 @@ void testKnapsack01With1DArraySelectedItems2() {
8787
var result = solution.knapsack01With1DArraySelected(n, w, weights, profits);
8888
assertArrayEquals(expectedResult, result);
8989
}
90+
91+
@Test
92+
void testKnapsackUnbounded() {
93+
int n = 4;
94+
int w = 8;
95+
var weights = new int[]{1, 2, 3, 5};
96+
var profits = new int[]{1, 4, 7, 10};
97+
var result = solution.knapsackUnbounded(n, w, weights, profits);
98+
assertEquals(18, result);
99+
}
90100
}

0 commit comments

Comments
 (0)