Skip to content

Commit 4795c09

Browse files
committed
Added 0/1 Knapsack Algorithm using Dynamic Programming in Java
1 parent 8726d40 commit 4795c09

File tree

1 file changed

+42
-20
lines changed

1 file changed

+42
-20
lines changed

src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java

Lines changed: 42 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,53 +3,75 @@
33
import java.util.Arrays;
44

55
/**
6-
* A Dynamic Programming based solution for the 0-1 Knapsack problem.
7-
* This class provides a method, `knapSack`, that calculates the maximum value that can be
8-
* obtained from a given set of items with weights and values, while not exceeding a
9-
* given weight capacity.
6+
* 0/1 Knapsack Problem - Dynamic Programming solution.
107
*
11-
* @see <a href="https://en.wikipedia.org/?title=0-1_Knapsack_problem">0-1 Knapsack Problem </a>
8+
* This algorithm solves the classic optimization problem where we have n items,
9+
* each with a weight and a value. The goal is to maximize the total value
10+
* without exceeding the knapsack's weight capacity.
11+
*
12+
* Time Complexity: O(n * W)
13+
* Space Complexity: O(W)
14+
*
15+
* Example:
16+
* values = {60, 100, 120}
17+
* weights = {10, 20, 30}
18+
* W = 50
19+
* Output: 220
20+
*
21+
* @author Arpita
22+
* @see <a href="https://en.wikipedia.org/wiki/Knapsack_problem">Knapsack Problem</a>
1223
*/
1324
public final class Knapsack {
1425

15-
private Knapsack() {
16-
}
26+
private Knapsack() {}
1727

28+
/**
29+
* Validates the input to ensure correct constraints.
30+
*/
1831
private static void throwIfInvalidInput(final int weightCapacity, final int[] weights, final int[] values) {
1932
if (weightCapacity < 0) {
2033
throw new IllegalArgumentException("Weight capacity should not be negative.");
2134
}
2235
if (weights == null || values == null || weights.length != values.length) {
23-
throw new IllegalArgumentException("Input arrays must not be null and must have the same length.");
36+
throw new IllegalArgumentException("Weights and values must be non-null and of the same length.");
2437
}
2538
if (Arrays.stream(weights).anyMatch(w -> w <= 0)) {
26-
throw new IllegalArgumentException("Input array should not contain non-positive weight(s).");
39+
throw new IllegalArgumentException("Weights must be positive.");
2740
}
2841
}
2942

3043
/**
31-
* Solves the 0-1 Knapsack problem using Dynamic Programming.
44+
* Solves the 0/1 Knapsack problem using Dynamic Programming (bottom-up approach).
3245
*
3346
* @param weightCapacity The maximum weight capacity of the knapsack.
34-
* @param weights An array of item weights.
35-
* @param values An array of item values.
36-
* @return The maximum value that can be obtained without exceeding the weight capacity.
37-
* @throws IllegalArgumentException If the input arrays are null or have different lengths.
47+
* @param weights The array of item weights.
48+
* @param values The array of item values.
49+
* @return The maximum total value achievable without exceeding capacity.
3850
*/
39-
public static int knapSack(final int weightCapacity, final int[] weights, final int[] values) throws IllegalArgumentException {
51+
public static int knapSack(final int weightCapacity, final int[] weights, final int[] values) {
4052
throwIfInvalidInput(weightCapacity, weights, values);
4153

42-
// DP table to store the state of the maximum possible return for a given weight capacity.
4354
int[] dp = new int[weightCapacity + 1];
4455

56+
// Fill dp[] array iteratively
4557
for (int i = 0; i < values.length; i++) {
46-
for (int w = weightCapacity; w > 0; w--) {
47-
if (weights[i] <= w) {
48-
dp[w] = Math.max(dp[w], dp[w - weights[i]] + values[i]);
49-
}
58+
for (int w = weightCapacity; w >= weights[i]; w--) {
59+
dp[w] = Math.max(dp[w], dp[w - weights[i]] + values[i]);
5060
}
5161
}
5262

5363
return dp[weightCapacity];
5464
}
65+
66+
/**
67+
* Example main method for demonstration.
68+
*/
69+
public static void main(String[] args) {
70+
int[] values = {60, 100, 120};
71+
int[] weights = {10, 20, 30};
72+
int weightCapacity = 50;
73+
74+
int maxValue = knapSack(weightCapacity, weights, values);
75+
System.out.println("Maximum value = " + maxValue); // Output: 220
76+
}
5577
}

0 commit comments

Comments
 (0)