Maximum sum of minimums of pairs in an array
Last Updated :
07 Mar, 2022
Given an array arr[] of N integers where N is even, the task is to group the array elements in the pairs (X1, Y1), (X2, Y2), (X3, Y3), … such that the sum min(X1, Y1) + min(X2, Y2) + min(X3, Y3) + … is maximum.
Examples:
Input: arr[] = {1, 5, 3, 2}
Output: 4
(1, 5) and (3, 2) -> 1 + 2 = 3
(1, 3) and (5, 2) -> 1 + 2 = 3
(1, 2) and (5, 3) -> 1 + 3 = 4
Input: arr[] = {1, 3, 2, 1, 4, 5}
Output: 7
Approach: No matter how the pairs are formed, the maximum element from the array will always be ignored as it will be the maximum element in every pair it is put into. Same goes for the second maximum element unless it is paired with the maximum element. So, to maximize the sum an optimal approach will be to sort the array and start making pairs in order starting from the maximum element.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxSum( int a[], int n)
{
sort(a, a + n);
int sum = 0;
for ( int i = 0; i < n - 1; i += 2) {
sum += a[i];
}
return sum;
}
int main()
{
int arr[] = { 1, 3, 2, 1, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxSum(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG
{
static int maxSum( int a[], int n)
{
Arrays.sort(a);
int sum = 0 ;
for ( int i = 0 ; i < n - 1 ; i += 2 )
{
sum += a[i];
}
return sum;
}
public static void main(String[] args)
{
int arr[] = { 1 , 3 , 2 , 1 , 4 , 5 };
int n = arr.length;
System.out.println(maxSum(arr, n));
}
}
|
Python3
def maxSum(a, n) :
a.sort();
sum = 0 ;
for i in range ( 0 , n - 1 , 2 ) :
sum + = a[i];
return sum ;
if __name__ = = "__main__" :
arr = [ 1 , 3 , 2 , 1 , 4 , 5 ];
n = len (arr);
print (maxSum(arr, n));
|
C#
using System;
class GFG
{
static int maxSum( int []a, int n)
{
Array.Sort(a);
int sum = 0;
for ( int i = 0; i < n - 1; i += 2)
{
sum += a[i];
}
return sum;
}
public static void Main(String[] args)
{
int []arr = { 1, 3, 2, 1, 4, 5 };
int n = arr.Length;
Console.WriteLine(maxSum(arr, n));
}
}
|
Javascript
<script>
function maxSum(a, n) {
a.sort((a, b) => a - b);
let sum = 0;
for (let i = 0; i < n - 1; i += 2) {
sum += a[i];
}
return sum;
}
let arr = [1, 3, 2, 1, 4, 5];
let n = arr.length;
document.write(maxSum(arr, n));
</script>
|
Time Complexity: O(n logn)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...