Suppose we have an array of 2n number of integers, we have to group these integers into n pairs of integer, like (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i in range 1 to n as large as possible. So if the input is [1, 4, 3, 2], then output will be 4. So n is 2. And the maximum sum of pairs is 4. This is min(1, 2) + min(3, 4) = 4
To solve this, we will follow these steps −
- let n is the size of the array
- sort the array
- answer := 0
- for i in range 0 to n, jump by 2
- answer := answer + array[i]
- return answer
Example
Let us see the following implementation to get better understanding −
class Solution(object): def arrayPairSum(self, a): """ :type nums: List[int] :rtype: int """ n = len(a) a.sort() ans = 0 for i in range(0,n,2): ans += a[i] return ans ob1 = Solution() print(ob1.arrayPairSum([1,4,3,2]))
Input
[1,4,3,2]
Output
4