Maximize sum of second minimums of each K length partitions of the array
Last Updated :
31 May, 2021
Given an array A[] of size N and a positive integer K ( which will always be a factor of N), the task is to find the maximum possible sum of the second smallest elements of each partition of the array by partitioning the array into (N / K) partitions of equal size.
Examples:
Input: A[] = {2, 3, 1, 4, 7, 5, 6, 1}, K = 4
Output: 7
Explanation: Split the array as {1, 2, 3, 4} and {1, 5, 6, 7}. Therefore, sum = 2 + 5 = 7, which is the maximum possible sum.
Input: A[] = {12, 43, 15, 32, 45, 23}, K = 3
Output : 66
Explanation: Split the array as {12, 23, 32} and {15, 43, 45}. Therefore, sum = 23 + 43 = 66, which is the maximum possible sum.
Approach: The idea is to sort the given array in ascending order and in order to maximize the required sum, divide the first N / K elements of A[] to each of the arrays as their first term, then choose every (K – 1)th element of A[] starting from N/K.
Follow the steps below to solve the problem:
- Sort the array A[] in increasing order.
- Initialize sum with 0 to store the required sum.
- Now, initialize a variable i with N / K.
- While i is less than N, perform the following steps:
- Increment sum by A[i].
- Increment i by K – 1.
- After traversing, print sum as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findSum( int A[], int N, int K)
{
sort(A, A + N);
int sum = 0;
for ( int i = N / K; i < N; i += K - 1) {
sum += A[i];
}
cout << sum;
}
int main()
{
int K = 4;
int A[] = { 2, 3, 1, 4, 7, 5, 6, 1 };
int N = sizeof (A) / sizeof (A[0]);
findSum(A, N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void findSum( int A[], int N, int K)
{
Arrays.sort(A);
int sum = 0 ;
for ( int i = N / K; i < N; i += K - 1 )
{
sum += A[i];
}
System.out.print(sum);
}
public static void main(String[] args)
{
int K = 4 ;
int A[] = { 2 , 3 , 1 , 4 , 7 , 5 , 6 , 1 };
int N = A.length;
findSum(A, N, K);
}
}
|
Python3
def findSum(A, N, K):
A.sort();
sum = 0 ;
for i in range (N / / K, N, K - 1 ):
sum + = A[i];
print ( sum );
if __name__ = = '__main__' :
K = 4 ;
A = [ 2 , 3 , 1 , 4 , 7 , 5 , 6 , 1 ];
N = len (A);
findSum(A, N, K);
|
C#
using System;
class GFG{
static void findSum( int []A, int N, int K)
{
Array.Sort(A);
int sum = 0;
for ( int i = N / K; i < N; i += K - 1)
{
sum += A[i];
}
Console.Write(sum);
}
public static void Main(String[] args)
{
int K = 4;
int []A = { 2, 3, 1, 4, 7, 5, 6, 1 };
int N = A.Length;
findSum(A, N, K);
}
}
|
Javascript
<script>
function findSum(A, N, K)
{
A.sort();
let sum = 0;
for (let i = N / K; i < N; i += K - 1)
{
sum += A[i];
}
document.write(sum);
}
let K = 4;
let A = [ 2, 3, 1, 4, 7, 5, 6, 1 ];
let N = A.length;
findSum(A, N, K);
</script>
|
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...