Skip to content

Commit 7326ab2

Browse files
authored
Add Space Optimized Solution to Subset sum problem (#5612)
1 parent 79544c8 commit 7326ab2

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
/*
3+
The Sum of Subset problem determines whether a subset of elements from a
4+
given array sums up to a specific target value.
5+
*/
6+
public final class SubsetSumSpaceOptimized {
7+
private SubsetSumSpaceOptimized() {
8+
}
9+
/**
10+
* This method checks whether the subset of an array
11+
* contains a given sum or not. This is an space
12+
* optimized solution using 1D boolean array
13+
* Time Complexity: O(n * sum), Space complexity: O(sum)
14+
*
15+
* @param arr An array containing integers
16+
* @param sum The target sum of the subset
17+
* @return True or False
18+
*/
19+
public static boolean isSubsetSum(int[] arr, int sum) {
20+
int n = arr.length;
21+
// Declare the boolean array with size sum + 1
22+
boolean[] dp = new boolean[sum + 1];
23+
24+
// Initialize the first element as true
25+
dp[0] = true;
26+
27+
// Find the subset sum using 1D array
28+
for (int i = 0; i < n; i++) {
29+
for (int j = sum; j >= arr[i]; j--) {
30+
dp[j] = dp[j] || dp[j - arr[i]];
31+
}
32+
}
33+
return dp[sum];
34+
}
35+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
import static org.junit.jupiter.api.Assertions.assertFalse;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
public class SubsetSumSpaceOptimizedTest {
9+
10+
@Test
11+
void basicCheck() {
12+
assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {7, 3, 2, 5, 8}, 14));
13+
assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {4, 3, 2, 1}, 5));
14+
assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {1, 7, 2, 9, 10}, 13));
15+
assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[] {1, 2, 7, 10, 9}, 14));
16+
assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[] {2, 15, 1, 6, 7}, 4));
17+
}
18+
}

0 commit comments

Comments
 (0)