-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathSplit Array Largest Sum.cpp
55 lines (42 loc) · 1.16 KB
/
Split Array Largest Sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
Solution by Rahul Surana
***********************************************************
Given an array nums which consists of non-negative integers and an integer m,
you can split the array into m non-empty continuous subarrays.
Write an algorithm to minimize the largest sum among these m subarrays.
***********************************************************
*/
#include <bits/stdc++.h>
class Solution {
public:
int splitArray(vector<int>& nums, int m) {
int l = 0,r = 0;
for(auto n:nums){
l = max(n,l);
r += n;
}
auto f = [&](int z){
int g = 0;
int k = 0;
for(auto n : nums){
k+=n;
if(k > z) {
g++;
k = n;
}
}
// cout << z <<" "<<g <<"\n";
return g;
};
while(l<=r){
int mid = (l+r)/2;
if(f(mid) >= m){
l = mid+1;
}
else{
r = mid-1;
}
}
return l;
}
};