Optimised Space Complexity To O(sum) #5651
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
fixes #5600
Problem:
This PR implements a solution to the "Subset Sum Equals to K" problem using dynamic programming while optimizing space complexity from O(n * sum) to O(sum). The problem is to determine whether there is a subset of a given array whose sum is exactly equal to a target integer
K
.Approach:
The standard DP approach for the subset sum problem involves creating a 2D table where each entry dp[i][j] represents whether a subset of the first
i
elements of the array can sum toj
. This has a space complexity of O(n * sum), wheren
is the number of elements in the array andsum
is the target sum.To optimize space complexity, we can use a 1D array of size
sum + 1
instead of the 2D table. The key idea is that the current state of the DP table only depends on the previous row (i.e., whether the sum was possible with or without the current element). Thus, we can update the DP array in reverse order, ensuring that we do not overwrite values that are still needed.Space Optimization:
The space-optimized approach reduces the space complexity to O(sum) by reusing a 1D DP array. At each iteration, we update the DP array from right to left to ensure we only use the previous values from the last iteration.
clang-format -i --style=file path/to/your/file.java