Wood Cut
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.
You couldn't cut wood into float length.
Example
For L=[232, 124, 456]
, k=7
, return 114
.
Analysis:
From 1 to Max(L), use binary search to find the maximum length;
1 public class Solution { 2 /** 3 *@param L: Given n pieces of wood with length L[i] 4 *@param k: An integer 5 *return: The maximum length of the small pieces. 6 */ 7 public int woodCut(int[] L, int k) { 8 if (L == null || L.length == 0) return 0; 9 int startLength = 1; 10 int endLength = maxLength(L); 11 12 while (startLength <= endLength) { 13 int mid = startLength + (endLength - startLength) / 2; 14 if (count(L, mid) >= k) { 15 startLength = mid + 1; 16 } else { 17 endLength = mid - 1; 18 } 19 } 20 return startLength - 1; // using startLength will make count(L, startLength) < k 21 } 22 23 public int count(int[] L, int length) { 24 int total = 0; 25 for (int i = 0; i < L.length; i++) { 26 total += L[i] / length; 27 } 28 return total; 29 } 30 31 public int maxLength(int[] L) { 32 int max = L[0]; 33 for (int i = 0; i < L.length; i++) { 34 max = Math.max(L[i], max); 35 } 36 return max; 37 } 38 }