-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack Problem
More file actions
59 lines (45 loc) · 1.74 KB
/
Copy pathKnapsack Problem
File metadata and controls
59 lines (45 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//Knapsack Problem (0/1)
import java.util.*;
public class Knapsack01 {
// Memo table to store results: dp[index][capacity]
private static int[][] dp;
public static int knapsack(int[] weights, int[] values, int capacity) {
int n = weights.length;
dp = new int[n][capacity + 1];
// Initialize dp with -1 (meaning not computed)
for (int i = 0; i < n; i++) {
Arrays.fill(dp[i], -1);
}
// Start recursion from index 0 and full capacity
return helper(weights, values, capacity, 0);
}
// Recursive helper function
private static int helper(int[] weights, int[] values, int capacity, int index) {
// Base case: no more items or no capacity left
if (index == weights.length || capacity == 0) {
return 0;
}
// Return cached result if already computed
if (dp[index][capacity] != -1) {
return dp[index][capacity];
}
// Option 1: skip current item
int skip = helper(weights, values, capacity, index + 1);
int pick = 0;
// Option 2: pick current item (if it fits)
if (weights[index] <= capacity) {
pick = values[index] + helper(weights, values, capacity - weights[index], index + 1);
}
// Store the max value obtained by picking or skipping
dp[index][capacity] = Math.max(pick, skip);
return dp[index][capacity];
}
// Driver code to test
public static void main(String[] args) {
int[] weights = {1, 3, 4, 5};
int[] values = {1, 4, 5, 7};
int capacity = 7;
int maxValue = knapsack(weights, values, capacity);
System.out.println("Maximum value in knapsack = " + maxValue);
}
}