-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay 14: Split Array Largest Sum.cpp
More file actions
39 lines (39 loc) · 993 Bytes
/
Copy pathDay 14: Split Array Largest Sum.cpp
File metadata and controls
39 lines (39 loc) · 993 Bytes
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
bool check(int mid, int array[], int n, int K)
{
int count = 0;
int sum = 0;
for (int i = 0; i < n; i++) {
if (array[i] > mid)
return false;
sum += array[i];
if (sum > mid) {
count++;
sum = array[i];
}
}
count++;
if (count <= K)
return true;
return false;
}
int splitArray(int array[], int n, int K) {
// code here
int* max = max_element(array, array + n);
int start = *max;
int end = 0;
for (int i = 0; i < n; i++) {
end += array[i];
}
int answer = 0;
while (start <= end) {
int mid = (start + end) / 2;
if (check(mid, array, n, K)) {
answer = mid;
end = mid - 1;
}
else {
start = mid + 1;
}
}
return answer;
}