Wood Cut
Description
Given n pieces of wood with length L[i] (integer array). Cut them into small pieces to guarantee you could have equal or more than k pieces with the same length. What is the longest length you can get from the n pieces of wood? Given L & k, return the maximum length of the small pieces.
Notice You couldn't cut wood into float length.
Example For L=[232, 124, 456], k=7, return 114.
Challenge
O(n log Len), where Len is the longest length of the wood.
Link
Method
- x
- x
Example
- 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> nums, int k) { // write your code here if (nums.empty()) { return 0; } int result = 0; int max_length = 0; // find max length we can cut for (int i = 0; i < nums.size(); ++i) { max_length = max(max_length, nums[i]); } // search result int start = 1; int end = max_length; while (start + 1 < end) { int mid = start + (end - start) / 2; // int curcut = cutCounter(nums, mid); if (curcut >= k) { start = mid; } else { end = mid; } } // we can cut more than k times, not the less if (cutCounter(nums, end) >= k) { return end; } else if (cutCounter(nums, start) >= k) { return start; } return 0; } private: int cutCounter(vector<int>& nums, int val) { if (val <= 0) { return 0; } int result = 0; for (int i = 0; i < nums.size(); ++i) { result += (nums[i]/val); } return result; } };
Similar problems
x
Tags
x