File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
src/main/java/com/thealgorithms/dynamicprogramming Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments