CN: Difference of subset sums is minimum
Problem
Intuition
Time Complexity
Space Complexity
Solution
Last updated
Last updated
O(n*totalSum) + O(n) + O(n)O(n)import java.util.*;
import java.io.*;
public class Solution {
public static int minSubsetSumDifference(int[] arr, int n) {
// This function finds the minimum difference between the sums of two subsets of a given set.
// Initialize the total sum of the array.
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// Initialize the boolean array to store whether a subset with a given sum is possible.
// The first element is always true since the sum of an empty subset is 0.
boolean[] prev = new boolean[totalSum + 1];
prev[0] = true;
// If the first element of the array is less than or equal to the total sum, then it is possible to
// have a subset with sum equal to the first element.
if (arr[0] <= totalSum) {
prev[arr[0]] = true;
}
// Iterate over the remaining elements of the array.
for (int ind = 1; ind < n; ind++) {
// Create a new boolean array to store whether a subset with a given sum is possible.
boolean[] curr = new boolean[totalSum + 1];
curr[0] = true;
// Iterate over all possible sums.
for (int target = 1; target <= totalSum; target++) {
// If the current element is less than or equal to the target sum, then it is possible to
// have a subset with sum equal to the target sum by including the current element.
boolean notPick = prev[target];
boolean pick = false;
if (arr[ind] <= target) {
pick = prev[target - arr[ind]];
}
// Set the current element in the boolean array to true if it is possible to have a subset
// with sum equal to the target sum by including or excluding the current element.
curr[target] = pick || notPick;
}
// Update the previous boolean array with the current boolean array.
prev = curr;
}
// Initialize the minimum difference between the sums of two subsets.
int mini = Integer.MAX_VALUE;
// Iterate over all possible sums that are less than or equal to half of the total sum.
for (int i = 0; i <= totalSum / 2; i++) {
// If it is possible to have a subset with sum equal to i, then update the minimum difference.
if (prev[i] == true) {
int diff = Math.abs(i - (totalSum - i));
mini = Math.min(diff, mini);
}
}
// Return the minimum difference between the sums of two subsets.
return mini;
}
}