Skip to content

Commit aaa3fcb

Browse files
committed
Created a file
1 parent 5393ba4 commit aaa3fcb

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
/*
8+
Space Optimized solution using 1D boolean array
9+
Time Complexity: O(n * sum)
10+
Space complexity: O(sum)
11+
*/
12+
public static boolean isSubsetSum(int[] arr, int sum) {
13+
int n = arr.length;
14+
// Declare the boolean array with size sum + 1
15+
boolean[] dp = new boolean[sum + 1];
16+
17+
// Initialize the first element as true
18+
dp[0] = true;
19+
20+
// Find the subset sum using 1D array
21+
for (int i = 0; i < n; i++) {
22+
for (int j = sum; j >= arr[i]; j--) {
23+
dp[j] = dp[j] || dp[j - arr[i]];
24+
}
25+
}
26+
return dp[sum];
27+
}
28+
}

0 commit comments

Comments
 (0)