Skip to content

Commit 2d34bc1

Browse files
authored
Optimised Space Complexity To O(sum) (TheAlgorithms#5651)
* Optimised Space Complexity To O(sum) * Fixes Clang Format * Optimised Space Complexity To Use a Single DP Array
1 parent 0603acc commit 2d34bc1

File tree

1 file changed

+13
-16
lines changed

1 file changed

+13
-16
lines changed

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

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,28 +9,25 @@ private SubsetSum() {
99
*
1010
* @param arr the array containing integers.
1111
* @param sum the target sum of the subset.
12-
* @return {@code true} if a subset exists that sums to the given value, otherwise {@code false}.
12+
* @return {@code true} if a subset exists that sums to the given value,
13+
* otherwise {@code false}.
1314
*/
1415
public static boolean subsetSum(int[] arr, int sum) {
1516
int n = arr.length;
16-
boolean[][] isSum = new boolean[n + 1][sum + 1];
1717

18-
// Initialize the first column to true since a sum of 0 can always be achieved with an empty subset.
19-
for (int i = 0; i <= n; i++) {
20-
isSum[i][0] = true;
21-
}
18+
// Initialize a single array to store the possible sums
19+
boolean[] isSum = new boolean[sum + 1];
20+
21+
// Mark isSum[0] = true since a sum of 0 is always possible with 0 elements
22+
isSum[0] = true;
2223

23-
// Fill the subset sum matrix
24-
for (int i = 1; i <= n; i++) {
25-
for (int j = 1; j <= sum; j++) {
26-
if (arr[i - 1] <= j) {
27-
isSum[i][j] = isSum[i - 1][j] || isSum[i - 1][j - arr[i - 1]];
28-
} else {
29-
isSum[i][j] = isSum[i - 1][j];
30-
}
24+
// Iterate through each Element in the array
25+
for (int i = 0; i < n; i++) {
26+
// Traverse the isSum array backwards to prevent overwriting values
27+
for (int j = sum; j >= arr[i]; j--) {
28+
isSum[j] = isSum[j] || isSum[j - arr[i]];
3129
}
3230
}
33-
34-
return isSum[n][sum];
31+
return isSum[sum];
3532
}
3633
}

0 commit comments

Comments
 (0)