Maximize sum of second minimums in all quadruples of a given array
Last Updated :
10 Aug, 2022
Given an array arr[] of length N, the task is to select a quadruple (i, j, k, l) and calculate the sum of the second minimums of all possible quadruples.
Note: It is guaranteed that N is a multiple of 4 and each array element can be part of a single quadruple.
Examples:
Input: arr[] = {7, 4, 5, 2, 3, 1, 5, 9}
Output: 8
Explanation:
Quadruple 1: {7, 1, 5, 9} => 2nd Minimum value = 5.
Quadruple 2: {4, 5, 2, 3} => 2nd Minimum value = 3.
Therefore, the maximum possible sum is 8.
Input: arr[] = {7, 4, 3, 3}
Output: 3
Approach: The idea is to use Greedy Approach to solve this problem. Below are the steps:
Below is the implementation of the above approach:
C++
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void maxPossibleSum( int arr[], int N)
{
sort(arr, arr + N);
int sum = 0;
int j = N - 3;
while (j >= 0)
{
sum += arr[j];
j -= 3;
}
cout << sum;
}
int main()
{
int arr[] = { 7, 4, 5, 2, 3, 1, 5, 9 };
int N = 8;
maxPossibleSum(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static void maxPossibleSum( int [] arr, int N)
{
Arrays.sort(arr);
int sum = 0 ;
int j = N - 3 ;
while (j >= 0 ) {
sum += arr[j];
j -= 3 ;
}
System.out.println(sum);
}
public static void main(String[] args)
{
int [] arr = { 7 , 4 , 5 , 2 , 3 , 1 , 5 , 9 };
int N = arr.length;
maxPossibleSum(arr, N);
}
}
|
Python3
def maxPossibleSum(arr, N):
arr.sort()
sum = 0
j = N - 3
while (j > = 0 ):
sum + = arr[j]
j - = 3
print ( sum )
if __name__ = = "__main__" :
arr = [ 7 , 4 , 5 , 2 , 3 , 1 , 5 , 9 ]
N = 8
maxPossibleSum(arr, N)
|
C#
using System;
public class GFG
{
public static void maxPossibleSum( int [] arr, int N)
{
Array.Sort(arr);
int sum = 0;
int j = N - 3;
while (j >= 0)
{
sum += arr[j];
j -= 3;
}
Console.WriteLine(sum);
}
public static void Main(String[] args)
{
int [] arr = { 7, 4, 5, 2, 3, 1, 5, 9 };
int N = arr.Length;
maxPossibleSum(arr, N);
}
}
|
Javascript
<script>
function maxPossibleSum(arr, N)
{
arr.sort();
let sum = 0;
let j = N - 3;
while (j >= 0) {
sum += arr[j];
j -= 3;
}
document.write(sum);
}
let arr = [ 7, 4, 5, 2, 3, 1, 5, 9 ];
let N = arr.length;
maxPossibleSum(arr, N);
</script>
|
Time Complexity: O(N*log(N))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...