![]() |
VOOZH | about |
Given an integer array arr[], divide it into two subsets such that the absolute difference between their sums is zero (i.e., both subsets have the same sum).
Note: It is always guaranteed that the array can be divided into two such subsets.
Examples:
Input: arr[] = [1, 2, 3, 4]
Output: [[1, 4], [2, 3]]
Explanation: The absolute difference between the sum of both subsets is 0Input: arr[] = [5, 10, 15]
Output: [[5, 10], [15]]
Explanation: The absolute difference between the sum of both subsets is 0
The idea is to reduce the partitioning problem into finding one subset of required size whose sum equals half of the total sum. The other subset is simply the remaining elements.
How to find the subset whose sum is equals to half of total sum?
First calculate the total sum of the array. Since equal division is guaranteed, the sum must be even, and the target for each subset is totalSum / 2.
Then, recursively search for one subset of size n/2 (n/2 or n/2+1 if n is odd) whose sum equals the target.
At each step, we either include the current element in the subset or skip it.
When the subset reaches required size and sum, we stop and store the result.
2 3 1 4