Open In App

Split array into K subarrays such that sum of maximum of all subarrays is maximized

Last Updated : 10 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print "-1".

Examples:

Input: arr[] = {5, 3, 2, 7, 6, 4}, N = 6, K = 3
Output: 18
              5
              3 2 7
              6 4
Explanation:
One way is to split the array at indices 0, 3 and 4.
Therefore, the subarrays formed are {5}, {3, 2, 7} and {6, 4}.
Therefore, sum of the maximum of each subarray = 5 + 7 + 6 =18 ( which is the maximum possible).

Input: arr[] = {1, 4, 5, 6, 1, 2}, N = 6, K = 2 
Output: 11

Approach: The given problem can be solved using Map data structure and Sorting techniques, based on the following observations: 

  • The maximum obtainable sum would be the sum of the K-largest elements of the array as it is always possible to divide the array into K segments in such a way that the maximum of each segment is one of the K-largest elements.
  • One way would be to break a segment as soon as one of the K-largest element is encountered.

Follow the steps below to solve the problem:

  • First, if N is less than K then print "-1" and then return.
  • Copy array into another array say temp[] and sort the array, temp[] in descending order.
  • Initialize a variable ans to 0, to store the maximum sum possible.
  • Also, Initialize a map say mp, to store the frequency of the K-largest elements.
  • Iterate in the range [0, K-1] using a variable say i, and in each iteration increment the ans by temp[i] and increment the count of temp[i] in map mp.
  • Initialize a vector of vectors say P to store a possible partition and a vector say V to store the elements of a partition.
  • Iterate in the range [0, N-1] and using a variable say i and perform the following steps:
    • Push the current element arr[i] in the vector V.
    • If mp[arr[i]] is greater than 0 then do the following:
      • Decrement K and count of arr[i] in the map mp by 1.
      • If K is equal to 0 i.e it is the last segment then push all the remaining elements of the array arr[] in V.
      • Now push the current segment V in the P.
  • Finally, after completing the above steps, print the maximum sum stores in variable ans and then partition stored in P.

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output: 
18
5 
3 2 7 
6 4

 

Time Complexity: O(N*log(N))
Auxiliary Space: O(N)

Related Topic: Subarrays, Subsequences, and Subsets in Array


Next Article

Similar Reads