Given an int array wood representing the length of n pieces of wood and an int k. It is required to cut these pieces of wood such that more or equal to k pieces of the same length len are cut. What is the longest len you can get?
比如五根木头长度分别为1,2,3,4,5,
要切出5段,最大长度是2
要切7段,最大长度是1
要切16段,切不了
比如五根木头长度分别为1,2,3,4,5,
要切出5段,最大长度是2
要切7段,最大长度是1
要切16段,切不了
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 | #include "misc.h" class Solution{ public: int getMaxLen(vector<int> woods, int k){ int l = *min_element(woods.begin(), woods.end()); int r = *max_element(woods.begin(), woods.end()); int maxLen = 0; while(l<=r){ int m = (l+r)/2; int cnt = 0; for(auto w:woods){ cnt += w/m; } if(cnt>=k){ maxLen = max(maxLen, m); l = m+1; }else{ r = m-1; } } return maxLen; } }; int main(){ Solution sol; vector<int> woods{1,2,3,4,5}; cout<<sol.getMaxLen(woods, 16)<<endl; return 0; } |
No comments:
Post a Comment