Skip to content

Commit 50095a6

Browse files
committed
Add 0/1 Knapsack Algorithm implementation using Dynamic Programming
1 parent 4858ec9 commit 50095a6

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package dynamicprogramming;
2+
/**
3+
* Implementation of the 0/1 Knapsack Problem using Dynamic Programming.
4+
*
5+
* Given weights and values of n items, put these items in a knapsack of capacity W
6+
* to get the maximum total value in the knapsack.
7+
*/
8+
public class Knapsack {
9+
10+
/**
11+
* Returns the maximum value that can be put in a knapsack of capacity W.
12+
*
13+
* @param W capacity of the knapsack
14+
* @param wt array of weights of the items
15+
* @param val array of values of the items
16+
* @param n number of items
17+
* @return maximum value achievable with given capacity
18+
*/
19+
public static int knapSack(int W, int[] wt, int[] val, int n) {
20+
int[][] dp = new int[n + 1][W + 1];
21+
22+
// Build table dp[][] in bottom-up manner
23+
for (int i = 0; i <= n; i++) {
24+
for (int w = 0; w <= W; w++) {
25+
if (i == 0 || w == 0) {
26+
dp[i][w] = 0; // Base case: no items or zero capacity
27+
} else if (wt[i - 1] <= w) {
28+
// Include the item or exclude it, choose max value
29+
dp[i][w] = Math.max(val[i - 1] + dp[i - 1][w - wt[i - 1]],
30+
dp[i - 1][w]);
31+
} else {
32+
// Item can't be included because it weighs more than capacity
33+
dp[i][w] = dp[i - 1][w];
34+
}
35+
}
36+
}
37+
38+
return dp[n][W];
39+
}
40+
41+
// Example usage and simple test case
42+
public static void main(String[] args) {
43+
int[] values = { 60, 100, 120 };
44+
int[] weights = { 10, 20, 30 };
45+
int capacity = 50;
46+
int n = values.length;
47+
48+
int maxValue = knapSack(capacity, weights, values, n);
49+
System.out.println("Maximum value in Knapsack = " + maxValue);
50+
// Expected output: 220
51+
}
52+
}

0 commit comments

Comments
 (0)