-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinMaxDivision
More file actions
44 lines (36 loc) · 1.08 KB
/
MinMaxDivision
File metadata and controls
44 lines (36 loc) · 1.08 KB
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
#include <algorithm>
#include <numeric>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int blockCount(int max, vector<int> &A) {
int current = 0;
int count = 1;
for (int x : A) {
if (current + x > max) {
current = x;
count++;
} else {
current += x;
}
}
return count;
}
int solution(int K, int M, vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
int lower_bound = *std::max_element(A.begin(), A.end());
int upper_bound = std::accumulate(A.begin(), A.end(), 0);
if (K == 1) return upper_bound;
if (K >= A.size()) return lower_bound;
int smallestSum = 0;
while (lower_bound <= upper_bound) {
int mid = (upper_bound + lower_bound) / 2;
int numberOfBlock = blockCount(mid, A);
if (numberOfBlock > K) {
lower_bound = mid + 1;
} else if (numberOfBlock <= K) {
smallestSum = mid;
upper_bound = mid - 1;
}
}
return smallestSum;
}