@@ -9,28 +9,25 @@ private SubsetSum() {
9
9
*
10
10
* @param arr the array containing integers.
11
11
* @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}.
13
14
*/
14
15
public static boolean subsetSum (int [] arr , int sum ) {
15
16
int n = arr .length ;
16
- boolean [][] isSum = new boolean [n + 1 ][sum + 1 ];
17
17
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 ;
22
23
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 ]];
31
29
}
32
30
}
33
-
34
- return isSum [n ][sum ];
31
+ return isSum [sum ];
35
32
}
36
33
}
0 commit comments