-
Notifications
You must be signed in to change notification settings - Fork 257
/
wood-cut.cpp
41 lines (36 loc) · 973 Bytes
/
wood-cut.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
// Time: O(nlogL)
// Space: O(1)
class Solution {
public:
/**
*@param L: Given n pieces of wood with length L[i]
*@param k: An integer
*return: The maximum length of the small pieces.
*/
int woodCut(vector<int> L, int k) {
const int n = L.size();
if (n == 0) {
return 0;
}
int left = 1, right = *max_element(L.cbegin(), L.cend());
while (left <= right) {
const auto mid = left + (right - left) / 2;
// Find the smallest x, s.t. pieceCount(x) < k <= pieceCound(x - 1)
if (pieceCount(L, mid) < k) {
right = mid - 1;
} else {
left = mid + 1;
}
}
// The max length is x - 1
return left - 1;
}
private:
int pieceCount(vector<int>& L, int x) {
int cnt = 0;
for (const auto& len : L) {
cnt += len / x;
}
return cnt;
}
};