LintCode : 木材加工

木材加工

  •  描述
  •  笔记
  •  数据
  •  评测

有一些原木,现在想把这些木头切割成一些长度相同的小段木头,需要得到的小段的数目至少为 k。当然,我们希望得到的小段越长越好,你需要计算能够得到的小段木头的最大长度。

 注意事项

木头长度的单位是厘米。原木的长度都是正整数,我们要求切割得到的小段木头的长度也要求是整数。无法切出要求至少 k 段的,则返回 0 即可。

您在真实的面试中是否遇到过这个题? 
Yes
样例

有3根木头[232, 124, 456]k=7, 最大长度为114.

挑战 
标签 

  • 先将所有的长度加起来,算出一个平均值,作为标准stand
  • 在每个数组中的长度划分,将整数部分相加若是符合>=k段,返回
  • 否则stand--,如此递归
  •   /**
         *@param L: Given n pieces of wood with length L[i]
         *@param k: An integer
         *return: The maximum length of the small pieces.
         */
        public int woodCut(int[] L, int k) {
            // write your code here
            int result = 0;
            if (L == null || L.length == 0) {
                return 0;
            }
            long totalLength = 0;
            for (int i = 0; i < L.length; i++) {
                totalLength += L[i];
            }
            int stand = (int) Math.floor(totalLength / k);
            while (stand > 0) {
                int totalK = 0;
                for (int i = 0; i < L.length; i++) {
                    totalK += Math.floor(L[i] / stand);
                }
                if (totalK >= k) {
                    result = stand;
                    break;
                } else {
                    stand--;
                }
            }
            return result;
        }
    


你可能感兴趣的:(LintCode : 木材加工)