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

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

  • 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

    • 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 
using namespace std;
bool ok(vector & 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 & 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  v = {2, 4, 3, 5, 12};
   int k = 2;
   cout 

Input

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

Output

14
Updated on: 2020-12-23T06:17:00+05:30

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements