-
Notifications
You must be signed in to change notification settings - Fork 19.4k
/
SubsetSum.java
33 lines (28 loc) · 1.05 KB
/
SubsetSum.java
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
package com.thealgorithms.dynamicprogramming;
public final class SubsetSum {
private SubsetSum() {
}
/**
* Test if a set of integers contains a subset that sums to a given integer.
*
* @param arr the array containing integers.
* @param sum the target sum of the subset.
* @return {@code true} if a subset exists that sums to the given value,
* otherwise {@code false}.
*/
public static boolean subsetSum(int[] arr, int sum) {
int n = arr.length;
// Initialize a single array to store the possible sums
boolean[] isSum = new boolean[sum + 1];
// Mark isSum[0] = true since a sum of 0 is always possible with 0 elements
isSum[0] = true;
// Iterate through each Element in the array
for (int i = 0; i < n; i++) {
// Traverse the isSum array backwards to prevent overwriting values
for (int j = sum; j >= arr[i]; j--) {
isSum[j] = isSum[j] || isSum[j - arr[i]];
}
}
return isSum[sum];
}
}