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)
- Maximum possible difference of two subsets of an array
- Minimize the absolute difference of sum of two subsets
- Maximum difference between two subsets of m elements
- Minimum difference between max and min of all K-size subsets
- k size subsets with maximum difference d between max and min
- Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
- Find subarray with given sum with negatives allowed in constant space
- Index Mapping (or Trivial Hashing) with negatives allowed
- Sum of subsets of all the subsets of an array | O(3^N)
- Sum of subsets of all the subsets of an array | O(N)
- Sum of subsets of all the subsets of an array | O(2^N)
- Maximize the sum of arr[i]*i
- Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l
- Subsets having Sum between A and B
- Sum of XOR of all possible subsets
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.