-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwood_cut.cpp
More file actions
56 lines (49 loc) · 1.28 KB
/
wood_cut.cpp
File metadata and controls
56 lines (49 loc) · 1.28 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
45
46
47
48
49
50
51
52
53
54
55
56
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 helper(vector<int> &L, int length) {
int count = 0;
for (int i = 0; i < L.size(); i++) {
count += L[i] / length;
}
return count;
}
int woodCut(vector<int> L, int k) {
// write your code here
if (L.size() == 0) {
return 0;
}
int max_length = 0;
int len = L.size();
for (int i = 0; i < len; i++) {
if (L[i] > max_length) {
max_length = L[i];
}
}
int start = 1;
int end = max_length;
int mid;
while (start + 1 < end) {
mid = start + (end - start) / 2;
int count = helper(L, mid);
if (count == k) {
start = mid;
} else if (count > k) {
start = mid;
} else if (count < k) {
end = mid;
}
}
if (helper(L, end) >= k) {
return end;
}
if (helper(L, start) >= k) {
return start;
}
return 0;
}
};