Program to find minimum largest sum of k sublists in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of numbers called nums and another value k. We can split the list into k non-empty sublists. We have to find the minimum largest sum of the k sublists.

So, if the input is like nums = [2, 4, 3, 5, 12] k = 2, then the output will be 14, as we can split the list like: [2, 4, 3, 5] and [12].

To solve this, we will follow these steps −

  • Define a function ok(), this will take array v, k, x,

  • cnt := 0, sum := 0

  • for each element i in v −

    • if sum + i > x, then −

      • sum := i

      • (increase cnt by 1)

    • Otherwise

      • sum := sum + i

  • return true when cnt <= k, otherwise false

  • From the main method do the following −

  • low := 0, ret := 0, high := 0

  • for each element i in nums

    • high := high + i

    • ret := ret + i

    • low := maximum of low and i

  • while low <= high, do −

    • mid := low + (high - low) / 2

    • if ok(nums, k - 1, mid) is true, then −

      • ret := mid

      • high := mid - 1

    • Otherwise

      • low := mid + 1

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool ok(vector <int>& v, int k, int x){
   int cnt = 0;
   int sum = 0;
   for(int i : v){
      if(sum + i > x){
         sum = i;
         cnt++;
      }
      else{
         sum += i;
      }
   }
   return cnt <= k;
}
int solve(vector<int>& nums, int k) {
   int low = 0;
   int ret = 0;
   int high = 0;
   for(int i : nums){
      high += i;
      ret += i;
      low = max(low, i);
   }
   while(low <= high){
      int mid = low + ( high - low) / 2;
      if(ok(nums, k - 1, mid)){
         ret = mid;
         high = mid - 1;
      }
      else{
         low = mid + 1;
      }
   }
   return ret;
}
int main(){
   vector<int> v = {2, 4, 3, 5, 12};
   int k = 2;
   cout << solve(v, k);
}

Input

{2, 4, 3, 5, 12}, 2

Output

14
raja
Published on 23-Dec-2020 10:46:22
Advertisements