Skip to content

Commit de39756

Browse files
authored
Merge pull request #152 from nishagii/feature/Knapsack-Problem-java
PR : Dynamic Programming Knapsack Problem in Java
2 parents 10e8181 + 41d7a7a commit de39756

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
public class KnapsackProblem {
2+
public static void main(String[] args) {
3+
int[] weights = {1, 2, 3};
4+
int[] values = {10, 15, 40};
5+
int capacity = 6;
6+
System.out.println("Maximum value in Knapsack = " + knapsack(weights, values, capacity));
7+
}
8+
9+
public static int knapsack(int[] weights, int[] values, int capacity) {
10+
int n = weights.length;
11+
int[][] dp = new int[n + 1][capacity + 1];
12+
13+
for (int i = 0; i <= n; i++) {
14+
for (int w = 0; w <= capacity; w++) {
15+
if (i == 0 || w == 0) {
16+
dp[i][w] = 0; // Base case: no items or no capacity
17+
} else if (weights[i - 1] <= w) {
18+
dp[i][w] = Math.max(dp[i - 1][w], // Exclude the item
19+
dp[i - 1][w - weights[i - 1]] + values[i - 1]); // Include the item
20+
} else {
21+
dp[i][w] = dp[i - 1][w]; // Exclude the item
22+
}
23+
}
24+
}
25+
return dp[n][capacity];
26+
}
27+
}

0 commit comments

Comments
 (0)