forked from black-shadows/LeetCode-Topicwise-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdivide-chocolate.cpp
32 lines (30 loc) · 855 Bytes
/
divide-chocolate.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
// Time: O(nlogn)
// Space: O(1)
class Solution {
public:
int maximizeSweetness(vector<int>& sweetness, int K) {
int left = *min_element(sweetness.cbegin(), sweetness.cend());
int right = accumulate(sweetness.cbegin(), sweetness.cend(), 0) / (K + 1);
while (left <= right) {
const auto& mid = left + (right - left) / 2;
if (!check(sweetness, K, mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
}
private:
bool check(const vector<int>& sweetness, int K, int x) {
int curr = 0, cuts = 0;
for (const auto& s : sweetness) {
curr += s;
if (curr >= x) {
++cuts;
curr = 0;
}
}
return cuts >= K + 1;
}
};