Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

Minimum subset sum difference

Given a set of integers, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum.

Solution

Code

int minSubsetSumDifference(vector<int>& arr, int n)
{
    int k = accumulate(arr.begin(),arr.end(), 0); // New code

    // Previous code for subset sum equals to K Problem
	vector<bool> prev(k + 1, false), curr(k + 1, false);
    prev[0] = true;
    curr[0] = true;
    if(arr[0]<=k) prev[arr[0]] = true;

    for (int i = 1; i < n; i++) {
        prev[0] = true; // from base case
        for (int target = 1; target <= k; target++) {
            bool take = false;
            if (arr[i] <= target)
                take = prev[target - arr[i]];
            bool notTake = prev[target];
            curr[target] = (take || notTake);
        }
        prev = curr;
    }

    // New code below
    int res = INT_MAX;
    for(int currSum = 0; currSum<=k/2; currSum++){
        if(prev[currSum]==true){
            res = min(res, k-2*currSum);
        }
    }
    return res;
}