Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
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 −
#includeusing 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}, 2Output
14
