Partition a set into two non-empty subsets such that the difference of subset sums is maximum
Last Updated :
21 Apr, 2021
Given a set of integers S, the task is to divide the given set into two non-empty sets S1 and S2 such that the absolute difference between their sums is maximum, i.e., abs(sum(S1) – sum(S2)) is maximum.
Example:
Input: S[] = { 1, 2, 1 }
Output: 2
Explanation:
The subsets are {1} and {2, 1}. Their absolute difference is
abs(1 - (2+1)) = 2, which is maximum.
Input: S[] = { -2, 3, -1, 5 }
Output: 11
Explanation:
The subsets are {-1, -2} and {3, 5}. Their absolute difference is
abs((-1, -2) - (3+5)) = 11, which is maximum.
Naive Approach: Generate and store all the subsets of the set of integers and find the maximum absolute difference between the sum of the subset and the difference between the total sum of the set and the sum of that subset, i.e, abs(sum(S1) - (totalSum - sum(S1)).
Time Complexity: O(2N)
Auxiliary Space: O(2N)
Efficient Approach: To optimize the naive approach, the idea is to use some mathematical observations. The problem can be divided into two cases:
- If the set contains only positive integers or only negative integers, then the maximum difference is obtained by splitting the set such that one subset contains only the minimum element of the set and the other subset contains all the remaining elements of the set, i.e.,
abs((totalSum - min(S)) - min(S)) or abs(totalSum - 2×min(S)), where S is the set of integers
- If the set contains both positive and negative integers, then the maximum difference is obtained by splitting the set such that one subset contains all the positive integers and the other subset contains all the negative integers, i.e.,
abs(sum(S1) - sum(S2)) or abs(sum(S)), where S1, S2 is the set of positive and negative integers respectively.
Below is the implementation of the above approach:
C++
// C++ Program for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximum
// difference between the subset sums
int maxDiffSubsets(int arr[], int N)
{
// Stores the total
// sum of the array
int totalSum = 0;
// Checks for positive
// and negative elements
bool pos = false, neg = false;
// Stores the minimum element
// from the given array
int min = INT_MAX;
// Traverse the array
for (int i = 0; i < N; i++)
{
// Calculate total sum
totalSum += abs(arr[i]);
// Mark positive element
// present in the set
if (arr[i] > 0)
pos = true;
// Mark negative element
// present in the set
if (arr[i] < 0)
neg = true;
// Find the minimum
// element of the set
if (arr[i] < min)
min = arr[i];
}
// If the array contains both
// positive and negative elements
if (pos && neg)
return totalSum;
// Otherwise
else
return totalSum - 2 * min;
}
// Driver Code
int main()
{
// Given the array
int S[] = {1, 2, 1};
// Length of the array
int N = sizeof(S) / sizeof(S[0]);
if (N < 2)
cout << ("Not Possible");
else
// Function Call
cout << (maxDiffSubsets(S, N));
}
// This code is contributed by Chitranayal
Java
// Java Program for above approach
import java.util.*;
import java.lang.*;
class GFG {
// Function to return the maximum
// difference between the subset sums
static int maxDiffSubsets(int[] arr)
{
// Stores the total
// sum of the array
int totalSum = 0;
// Checks for positive
// and negative elements
boolean pos = false, neg = false;
// Stores the minimum element
// from the given array
int min = Integer.MAX_VALUE;
// Traverse the array
for (int i = 0; i < arr.length; i++) {
// Calculate total sum
totalSum += Math.abs(arr[i]);
// Mark positive element
// present in the set
if (arr[i] > 0)
pos = true;
// Mark negative element
// present in the set
if (arr[i] < 0)
neg = true;
// Find the minimum
// element of the set
if (arr[i] < min)
min = arr[i];
}
// If the array contains both
// positive and negative elements
if (pos && neg)
return totalSum;
// Otherwise
else
return totalSum - 2 * min;
}
// Driver Code
public static void main(String[] args)
{
// Given the array
int[] S = { 1, 2, 1 };
// Length of the array
int N = S.length;
if (N < 2)
System.out.println("Not Possible");
else
// Function Call
System.out.println(maxDiffSubsets(S));
}
}
Python3
# Python3 program for above approach
import sys
# Function to return the maximum
# difference between the subset sums
def maxDiffSubsets(arr):
# Stores the total
# sum of the array
totalSum = 0
# Checks for positive
# and negative elements
pos = False
neg = False
# Stores the minimum element
# from the given array
min = sys.maxsize
# Traverse the array
for i in range(len(arr)):
# Calculate total sum
totalSum += abs(arr[i])
# Mark positive element
# present in the set
if (arr[i] > 0):
pos = True
# Mark negative element
# present in the set
if (arr[i] < 0):
neg = True
# Find the minimum
# element of the set
if (arr[i] < min):
min = arr[i]
# If the array contains both
# positive and negative elements
if (pos and neg):
return totalSum
# Otherwise
else:
return totalSum - 2 * min
# Driver Code
if __name__ == '__main__':
# Given the array
S = [ 1, 2, 1 ]
# Length of the array
N = len(S)
if (N < 2):
print("Not Possible")
else:
# Function Call
print(maxDiffSubsets(S))
# This code is contributed by mohit kumar 29
C#
// C# Program for above approach
using System;
class GFG{
// Function to return the maximum
// difference between the subset sums
static int maxDiffSubsets(int[] arr)
{
// Stores the total
// sum of the array
int totalSum = 0;
// Checks for positive
// and negative elements
bool pos = false, neg = false;
// Stores the minimum element
// from the given array
int min = int.MaxValue;
// Traverse the array
for (int i = 0; i < arr.Length; i++)
{
// Calculate total sum
totalSum += Math.Abs(arr[i]);
// Mark positive element
// present in the set
if (arr[i] > 0)
pos = true;
// Mark negative element
// present in the set
if (arr[i] < 0)
neg = true;
// Find the minimum
// element of the set
if (arr[i] < min)
min = arr[i];
}
// If the array contains both
// positive and negative elements
if (pos && neg)
return totalSum;
// Otherwise
else
return totalSum - 2 * min;
}
// Driver Code
public static void Main(String[] args)
{
// Given the array
int[] S = {1, 2, 1};
// Length of the array
int N = S.Length;
if (N < 2)
Console.WriteLine("Not Possible");
else
// Function Call
Console.WriteLine(maxDiffSubsets(S));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// javascript Program for above approach
// Function to return the maximum
// difference between the subset sums
function maxDiffSubsets(arr) {
// Stores the total
// sum of the array
var totalSum = 0;
// Checks for positive
// and negative elements
var pos = false, neg = false;
// Stores the minimum element
// from the given array
var min = Number.MAX_VALUE;
// Traverse the array
for (i = 0; i < arr.length; i++) {
// Calculate total sum
totalSum += Math.abs(arr[i]);
// Mark positive element
// present in the set
if (arr[i] > 0)
pos = true;
// Mark negative element
// present in the set
if (arr[i] < 0)
neg = true;
// Find the minimum
// element of the set
if (arr[i] < min)
min = arr[i];
}
// If the array contains both
// positive and negative elements
if (pos && neg)
return totalSum;
// Otherwise
else
return totalSum - 2 * min;
}
// Driver Code
// Given the array
var S = [ 1, 2, 1 ];
// Length of the array
var N = S.length;
if (N < 2)
document.write("Not Possible");
else
// Function Call
document.write(maxDiffSubsets(S));
// This code is contributed by todaysgaurav
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Partition a set into two subsets such that the difference of subset sums is minimum Given an array arr[] of size n, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must have n-m elements and the value of abs(sum(Subset1) - sum(Subs
15+ min read
Partition into two subsets of lengths K and (N - k) such that the difference of sums is maximum Given an array of non-negative integers of length N and an integer K. Partition the given array into two subsets of length K and N - K so that the difference between the sum of both subsets is maximum. Examples : Input : arr[] = {8, 4, 5, 2, 10} k = 2 Output : 17 Explanation : Here, we can make firs
7 min read
Split N powers of 2 into two subsets such that their difference of sum is minimum Given an even number N, the task is to split all N powers of 2 into two sets such that the difference of their sum is minimum.Examples: Input: n = 4 Output: 6 Explanation: Here n = 4 which means we have 21, 22, 23, 24. The most optimal way to divide it into two groups with equal element is 24 + 21 i
6 min read
Divide array in two Subsets such that sum of square of sum of both subsets is maximum Given an integer array arr[], the task is to divide this array into two non-empty subsets such that the sum of the square of the sum of both the subsets is maximum and sizes of both the subsets must not differ by more than 1.Examples: Input: arr[] = {1, 2, 3} Output: 26 Explanation: Sum of Subset Pa
6 min read
Partition an array of non-negative integers into two subsets such that average of both the subsets is equal Given an array of size N. The task is to partition the given array into two subsets such that the average of all the elements in both subsets is equal. If no such partition exists print -1. Otherwise, print the partitions. If multiple solutions exist, print the solution where the length of the first
14 min read