链接:LintCode 炼码 - ChatGPT!更高效的学习体验!
题解:九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧
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) {
// write your code here
if (l.size() <= 0) {
return 0;
}
int left = 0;
int right = l[0];
for (int i = 1; i < l.size(); ++i) {
right = max(right, l[i]);
}
while (left + 1 < right) {
int mid = left + (right-left)/2;
if (get_cut_count(l, mid) >=k) {
left = mid;
} else {
right = mid;
}
}
return get_cut_count(l, right) >= k ? right : left;
}
private:
int get_cut_count(std::vector<int>& l, int count) {
int result = 0;
for (auto& i : l) {
result += i/count;
}
cout << count << " " << result << endl;
return result;
}
};