Skip to content

Commit 6f67f1f

Browse files
committed
Optimised Space Complexity To O(sum)
1 parent 676d451 commit 6f67f1f

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

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

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,27 @@ private SubsetSum() {
1313
*/
1414
public static boolean subsetSum(int[] arr, int sum) {
1515
int n = arr.length;
16-
boolean[][] isSum = new boolean[n + 1][sum + 1];
1716

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-
}
17+
//Intialize Two Arrays to store current and prev states
18+
boolean[] isSumCurr = new boolean[sum + 1];
19+
boolean[] isSumPrev = new boolean[sum+1];
20+
21+
// Mark prev[0] = true as it is true to make sum = 0
22+
// using 0 elements
23+
isSumPrev[0] = true;
2224

2325
// Fill the subset sum matrix
2426
for (int i = 1; i <= n; i++) {
25-
for (int j = 1; j <= sum; j++) {
27+
for (int j = 0; j <= sum; j++) {
2628
if (arr[i - 1] <= j) {
27-
isSum[i][j] = isSum[i - 1][j] || isSum[i - 1][j - arr[i - 1]];
29+
isSumCurr[j] = isSumPrev[j] || isSumPrev[j - arr[i - 1]];
2830
} else {
29-
isSum[i][j] = isSum[i - 1][j];
31+
isSumCurr[j] = isSumPrev[j];
3032
}
3133
}
34+
isSumPrev = isSumCurr.clone();
3235
}
3336

34-
return isSum[n][sum];
37+
return isSumPrev[sum];
3538
}
3639
}

0 commit comments

Comments
 (0)