Split array into K subsets to maximize sum of their second largest elements
Last Updated :
10 Sep, 2021
Given an array arr[] consisting of N integers and an integer K, the task is to split the array into K subsets (N % K = 0) such that the sum of second largest elements of all subsets is maximized.
Examples:
Input: arr[] = {1, 3, 1, 5, 1, 3}, K = 2
Output: 4
Explanation: Splitting the array into the subsets {1, 1, 3} and {1, 3, 5} maximizes the sum of second maximum elements in the two arrays.
Input: arr[] = {1, 2, 5, 8, 6, 4, 3, 4, 9}, K = 3
Output: 17
Approach: The idea is to sort the array and keep adding every second element encountered while traversing the array in reverse, starting from the second largest element in the array, exactly K times. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void splitArray( int arr[], int n, int K)
{
sort(arr, arr + n);
int i = n - 1;
int result = 0;
while (K--) {
result += arr[i - 1];
i -= 2;
}
cout << result;
}
int main()
{
int arr[] = { 1, 3, 1, 5, 1, 3 };
int N = sizeof (arr)
/ sizeof (arr[0]);
int K = 2;
splitArray(arr, N, K);
return 0;
}
|
Java
import java.io.*;
import java.util.Arrays;
class GFG
{
static void splitArray( int arr[], int n, int K)
{
Arrays.sort(arr);
int i = n - 1 ;
int result = 0 ;
while (K-- != 0 )
{
result += arr[i - 1 ];
i -= 2 ;
}
System.out.print(result);
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 1 , 5 , 1 , 3 };
int N = arr.length;
int K = 2 ;
splitArray(arr, N, K);
}
}
|
Python3
def splitArray(arr, n, K):
arr.sort()
i = n - 1
result = 0
while (K > 0 ):
result + = arr[i - 1 ]
i - = 2
K - = 1
print (result)
if __name__ = = "__main__" :
arr = [ 1 , 3 , 1 , 5 , 1 , 3 ]
N = len (arr)
K = 2
splitArray(arr, N, K)
|
C#
using System;
class GFG
{
static void splitArray( int []arr, int n, int K)
{
Array.Sort(arr);
int i = n - 1;
int result = 0;
while (K-- != 0)
{
result += arr[i - 1];
i -= 2;
}
Console.Write(result);
}
public static void Main(String[] args)
{
int [] arr = { 1, 3, 1, 5, 1, 3 };
int N = arr.Length;
int K = 2;
splitArray(arr, N, K);
}
}
|
Javascript
<script>
function splitArray(arr, n, K)
{
arr.sort();
let i = n - 1;
let result = 0;
while (K-- != 0)
{
result += arr[i - 1];
i -= 2;
}
document.write(result);
}
let arr = [ 1, 3, 1, 5, 1, 3 ];
let N = arr.length;
let K = 2;
splitArray(arr, N, K);
</script>
|
Time complexity: O(N logN)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...