mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
Optimised Space Complexity To O(sum) (#5651)
* Optimised Space Complexity To O(sum) * Fixes Clang Format * Optimised Space Complexity To Use a Single DP Array
This commit is contained in:
@ -9,28 +9,25 @@ public final class SubsetSum {
|
|||||||
*
|
*
|
||||||
* @param arr the array containing integers.
|
* @param arr the array containing integers.
|
||||||
* @param sum the target sum of the subset.
|
* @param sum the target sum of the subset.
|
||||||
* @return {@code true} if a subset exists that sums to the given value, otherwise {@code false}.
|
* @return {@code true} if a subset exists that sums to the given value,
|
||||||
|
* otherwise {@code false}.
|
||||||
*/
|
*/
|
||||||
public static boolean subsetSum(int[] arr, int sum) {
|
public static boolean subsetSum(int[] arr, int sum) {
|
||||||
int n = arr.length;
|
int n = arr.length;
|
||||||
boolean[][] isSum = new boolean[n + 1][sum + 1];
|
|
||||||
|
|
||||||
// Initialize the first column to true since a sum of 0 can always be achieved with an empty subset.
|
// Initialize a single array to store the possible sums
|
||||||
for (int i = 0; i <= n; i++) {
|
boolean[] isSum = new boolean[sum + 1];
|
||||||
isSum[i][0] = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fill the subset sum matrix
|
// Mark isSum[0] = true since a sum of 0 is always possible with 0 elements
|
||||||
for (int i = 1; i <= n; i++) {
|
isSum[0] = true;
|
||||||
for (int j = 1; j <= sum; j++) {
|
|
||||||
if (arr[i - 1] <= j) {
|
|
||||||
isSum[i][j] = isSum[i - 1][j] || isSum[i - 1][j - arr[i - 1]];
|
|
||||||
} else {
|
|
||||||
isSum[i][j] = isSum[i - 1][j];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return isSum[n][sum];
|
// Iterate through each Element in the array
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
// Traverse the isSum array backwards to prevent overwriting values
|
||||||
|
for (int j = sum; j >= arr[i]; j--) {
|
||||||
|
isSum[j] = isSum[j] || isSum[j - arr[i]];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return isSum[sum];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user