public class Knapsack { public static void main(String[] args) { int[] weights = {1, 3, 4}; int[] values = {10, 40, 50}; int capacity = 6; int n = weights.length; int[][] dp = new int[n + 1][capacity + 1]; for (int i = 1; i <= n; i++) { for (int w = 1; w <= capacity; w++) { if (weights[i - 1] <= w) { dp[i][w] = Math.max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]); } else { dp[i][w] = dp[i - 1][w]; } } } for (int i = 0; i <= n; i++) { for (int w = 0; w <= capacity; w++) { System.out.print(dp[i][w] + " "); } System.out.println(); } } }
The DP table stores the maximum value achievable with the first i items and capacity w.
Row 1 considers only the first item (weight 1, value 10). It fills capacities >=1 with 10.
Row 2 adds the second item (weight 3, value 40), updating values where it improves the total.
Row 3 adds the third item (weight 4, value 50), further improving values where possible.
The DP table chooses to include an item only if it fits in the current capacity and improves the total value.
If including the item doesn't improve value or exceeds capacity, it is excluded.
The dp array is declared with size n x (capacity+1), but the loops access dp[i][w] with i from 1 to n inclusive.
Since dp has only n rows (0 to n-1), accessing dp[n][w] causes ArrayIndexOutOfBoundsException.
Possible combinations:
- Items 1,3,4: weights 2+1+3=6, values 12+10+15=37
- Items 2,3: weights 5+1=6, values 20+10=30
- Items 2,4: weights 5+3=8 (exceeds capacity)
- Items 1,4: weights 2+3=5, values 12+15=27
Maximum value is 37.
import java.util.Arrays; public class KnapsackMemo { static int[][] memo; public static int knapsack(int[] w, int[] v, int cap, int n) { if (n == 0 || cap == 0) return 0; if (memo[n][cap] != -1) return memo[n][cap]; if (w[n - 1] > cap) { memo[n][cap] = knapsack(w, v, cap, n - 1); } else { memo[n][cap] = Math.max(knapsack(w, v, cap, n - 1), v[n - 1] + knapsack(w, v, cap - w[n - 1], n - 1)); } return memo[n][cap]; } public static void main(String[] args) { int[] weights = {1, 2}; int[] values = {10, 15}; int capacity = 3; int n = weights.length; memo = new int[n + 1][capacity + 1]; for (int[] row : memo) Arrays.fill(row, -1); int result = knapsack(weights, values, capacity, n); System.out.println(result); } }
Items:
- Item 1: weight 1, value 10
- Item 2: weight 2, value 15
Capacity = 3
Possible combinations:
- Both items: weight 3, value 25
- Only item 2: weight 2, value 15
- Only item 1: weight 1, value 10
Maximum value is 25.
