Minimum sum obtained from groups of four elements from the given array
Given an array arr[] of N integers where N % 4 = 0, the task is to divide the integers into groups of four such that when the combined sum of the maximum two elements from all the groups is taken, it is minimum possible. Print the minimized sum.
Examples:
Input: arr[] = {1, 1, 2, 2}
Output: 4
The only group will be {1, 1, 2, 2}.
2 + 2 = 4
Input: arr[] = {1, 1, 10, 2, 2, 2, 1, 8}
Output: 21
{1, 1, 2, 1} and {10, 2, 2, 8} are the groups that will
give the minimum sum as 1 + 2 + 10 + 8 = 21.
Approach: In order to minimize the sum, the maximum four elements from the array must be in the same group because the maximum two elements will definitely be included in the sum no matter what group they are a part of but the next two maximum elements can be prevented if they are part of this group. Making groups, in the same manner, will give the minimum sum possible. So, sort the array in descending order and starting from the first element, make groups of four consecutive elements.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minSum( int arr[], int n)
{
int sum = 0;
sort(arr, arr + n, greater< int >());
for ( int i = 0; i < n; i++) {
if (i % 4 < 2)
sum = sum + arr[i];
}
return sum;
}
int main()
{
int arr[] = { 1, 1, 10, 2, 2, 2, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << minSum(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int minSum(Integer arr[], int n)
{
int sum = 0 ;
Arrays.sort(arr, Collections.reverseOrder());
for ( int i = 0 ; i < n; i++)
{
if (i % 4 < 2 )
sum = sum + arr[i];
}
return sum;
}
public static void main(String[] args)
{
Integer []arr = { 1 , 1 , 10 , 2 , 2 , 2 , 1 };
int n = arr.length;
System.out.println(minSum(arr, n));
}
}
|
Python3
def minSum(arr, n) :
sum = 0 ;
arr.sort(reverse = True )
for i in range (n) :
if (i % 4 < 2 ) :
sum + = arr[i];
return sum ;
if __name__ = = "__main__" :
arr = [ 1 , 1 , 10 , 2 , 2 , 2 , 1 ];
n = len (arr);
print (minSum(arr, n));
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int minSum( int []arr, int n)
{
int sum = 0;
Array.Sort(arr);
Array.Reverse(arr);
for ( int i = 0; i < n; i++)
{
if (i % 4 < 2)
sum = sum + arr[i];
}
return sum;
}
public static void Main(String[] args)
{
int []arr = { 1, 1, 10, 2, 2, 2, 1 };
int n = arr.Length;
Console.WriteLine(minSum(arr, n));
}
}
|
Javascript
<script>
function minSum(arr, n)
{
let sum = 0;
arr.sort( function (a, b){ return b-a});
for (let i = 0; i < n; i++) {
if (i % 4 < 2)
sum = sum + arr[i];
}
return sum;
}
let arr = [ 1, 1, 10, 2, 2, 2, 1 ];
let n = arr.length;
document.write(minSum(arr, n));
</script>
|
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
Last Updated :
19 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...