Skip to content

Added Space Optimized Solution to Subset sum problem #5612

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Oct 10, 2024
Merged
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.thealgorithms.dynamicprogramming;
/*
The Sum of Subset problem determines whether a subset of elements from a
given array sums up to a specific target value.
*/
public final class SubsetSumSpaceOptimized {
private SubsetSumSpaceOptimized() {
}
/**
* This method checks whether the subset of an array
* contains a given sum or not. This is an space
* optimized solution using 1D boolean array
* Time Complexity: O(n * sum), Space complexity: O(sum)
*
* @param arr An array containing integers
* @param sum The target sum of the subset
* @return True or False
*/
public static boolean isSubsetSum(int[] arr, int sum) {
int n = arr.length;
// Declare the boolean array with size sum + 1
boolean[] dp = new boolean[sum + 1];

// Initialize the first element as true
dp[0] = true;

// Find the subset sum using 1D array
for (int i = 0; i < n; i++) {
for (int j = sum; j >= arr[i]; j--) {
dp[j] = dp[j] || dp[j - arr[i]];
}
}
return dp[sum];
}
}