Given an array of integers, partition the array into two subsets such that the difference between their sums is minimized. Find this minimum difference.
Minimum Subset Sum Difference
- Description: Given an array of integers, partition the array into two subsets such that the difference between their sums is minimized. Find this minimum difference.
- Input: An array of integers
arr[]
. - Output: Return the minimum difference between the sums of the two subsets.
- Example:
- Input:
arr = [1, 6, 11, 5]
- Output:
1
(Partition[1, 5, 6]
and[11]
results in sums of 12 and 11, with a difference of 1)
- Input:
Minimum Subset Sum Difference
- java
public class MinimumSubsetSumDifference { public static int minSubsetSumDifference(int[] arr) { int sum = 0; for (int num : arr) sum += num; int target = sum / 2; boolean[] dp = new boolean[target + 1]; dp[0] = true; for (int num : arr) { for (int j = target; j >= num; j--) { dp[j] = dp[j] || dp[j - num]; } } int s1 = 0; for (int i = target; i >= 0; i--) { if (dp[i]) { s1 = i; break; } } int s2 = sum - s1; return Math.abs(s2 - s1); } public static void main(String[] args) { int[] arr = {1, 6, 11, 5}; System.out.println(minSubsetSumDifference(arr)); // Output: 1 } }
Comments
Post a Comment