-
Notifications
You must be signed in to change notification settings - Fork 28
/
Split_Array_Largest_Sum.cpp
67 lines (59 loc) · 1.8 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
56
57
58
59
60
61
62
63
64
65
66
67
class Solution {
bool valid(long target, vector<int>& arr, int m) {
int cnt = 1;
long long total = 0LL;
for(int i = 0; i < arr.size(); i++) {
total += arr[i];
if(total > target) {
total = arr[i];
cnt++;
if(cnt > m) {
return false;
}
}
}
return true;
}
// more efficient, utilize cumulative sum
bool valid2(long long target, vector<long long>& sums, int m) {
int count = 0, start = 1, end = (int)sums.size();
while (start < end) {
int left = start, right = end, mid = 0;
while (left <= right) {
mid = left + (right - left) / 2;
if (sums[mid] - sums[start - 1] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
if (++count > m) {
return false;
}
start = left;
}
return true;
};
public:
int splitArray(vector<int>& arr, int m) {
int maxi = 0;
int n = (int)arr.size();
vector<long long> sums(n + 1, 0LL);
for(int i = 0; i < n; i++) {
maxi = max(maxi, arr[i]);
sums[i + 1] = sums[i] + arr[i];
}
if(m == 1) return (int)sums[n];
if(m == arr.size()) return maxi;
long long left = maxi, right = sums[n];
while(left <= right) {
long long mid = left + (right - left) / 2LL;
if(valid2(mid, sums, m)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return (int)left;
}
};