Given an of integers of size N. The task is to separate these integers into two groups g1 and g2 such that (sum of elements of g1) – (sum of elements of g2) becomes maximum. Your task is to print the value of result. We may keep one subset as empty.
Input : 3, 7, -4, 10, -11, 2
Output : 37
g1: 3, 7, 10, 2
g2: -4, -11
result = ( 3 + 7 + 10 + 2 ) – ( -4 + -11) = 22 – (-15) = 37
Input : 2, 2, -2, -2
Output : 8
The idea is to group integers according to their sign value i.e., we group positive integers as g1 and negative integers as g2.
Since, – ( -g2 ) = +g2
Therefore, result becomes g1 + |g2|.
Time Complexity: O(n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Index Mapping (or Trivial Hashing) with negatives allowed
- Find subarray with given sum with negatives allowed in constant space
- Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
- Divide array in two Subsets such that sum of square of sum of both subsets is maximum
- Sum of subsets of all the subsets of an array | O(3^N)
- Sum of subsets of all the subsets of an array | O(2^N)
- Sum of subsets of all the subsets of an array | O(N)
- Partition a set into two subsets such that difference between max of one and min of other is minimized
- Split array into K subsets to maximize their sum of maximums and minimums
- Maximize count of subsets having product of smallest element and size of the subset at least X
- Maximum difference between two subsets of m elements
- Partition a set into two non-empty subsets such that the difference of subset sums is maximum
- Place the prisoners into cells to maximize the minimum difference between any two
- Maximize difference between the Sum of the two halves of the Array after removal of N elements
- Minimize the absolute difference of sum of two subsets
- Split N powers of 2 into two subsets such that their difference of sum is minimum
- Subsets of size K with product equal to difference of two perfect squares
- Maximum possible difference of two subsets of an array
- Minimum difference between max and min of all K-size subsets
- k size subsets with maximum difference d between max and min
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.