-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path410. Split Array Largest Sum.cpp
60 lines (57 loc) · 1.23 KB
/
410. 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
56
57
58
59
60
class Solution {
public:
// same as leetcode 1011
int maximum(vector<int> &w)
{
int mx = INT_MIN;
for(auto x : w)
mx = max( mx, x);
return mx;
}
int sum(vector<int> & w)
{
int sum=0;
for( auto x : w)
sum += x;
return sum;
}
bool isfeasible(int x , vector<int> weights , int days)
{
int sum = 0 , cnt =1 ;
for( auto w : weights)
{
if( sum + w <= x )
sum += w;
else
{
cnt++;
sum = w;
}
}
if( cnt <= days)
return true;
else
return false;
}
int splitArray(vector<int>& nums, int m) {
int l = maximum(nums);
int ans = 0;
long h = sum(nums);
while( l <= h )
{
long mid = (l +h )/2;
if( isfeasible(mid, nums,m) )
{
// cout<<mid <<endl;
ans = mid;
h = mid -1;
}
else
{
//cout<< mid <<" false"<<endl;
l = mid +1;
}
}
return ans;
}
};