Overview
This is a classic variation of the Subset Sum / 0-1 Knapsack problem. If the total sum is odd, it's impossible. If it's even, we just need to find ANY subset that sums to exactly `Total / 2`.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Determine if a given array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
This is a classic variation of the Subset Sum / 0-1 Knapsack problem. If the total sum is odd, it's impossible. If it's even, we just need to find ANY subset that sums to exactly `Total / 2`.
We use a 1D boolean array where `dp[j]` is `true` if a subset with sum `j` exists. The base case is `dp[0] = true`.
When optimizing to 1D, we MUST iterate the target sum `j` backwards (from `target` down to `num`). This ensures we don't use the same element multiple times.
For a given `num`, we can reach sum `j` if we could already reach sum `j - num`. So `dp[j] = dp[j] || dp[j - num]`.