import java.util.Arrays;
/**
* @author xnl
* @Description:
* @date: 2022/6/7 22:14
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[] piles = {30,11,23,4,20};
System.out.println(solution.minEatingSpeed(piles, 6));
}
public int minEatingSpeed(int[] piles, int h) {
int maxValue = Arrays.stream(piles).max().getAsInt();
if (piles.length == h){
return maxValue;
}
int left = 1, right = maxValue, k = maxValue;
while (left < right){
int speed = (left + right) >> 1;
int time = getTime(piles, speed);
// 证明这个速度可以吃完,看看能不能找到速度更块的
if (time <= h){
k = speed;
right = speed;
} else {
// 这个速度吃不完,咋办?吃的速度加一
left = speed + 1;
}
}
return k;
}
private int getTime(int[] piles, int speed){
int countTime = 0;
for (int pile : piles) {
int count = pile % speed == 0 ? pile / speed : (pile / speed )+ 1;
countTime += count;
}
return countTime;
}
}
力扣: 爱吃香蕉的珂珂
优化算法:解决Java堆数组吃饼干问题
于 2022-06-07 23:01:15 首次发布
本文介绍了一个关于Java编程中的算法问题,涉及如何在给定时间内以最小速度吃完不同数量的饼干。作者通过Solution类实现了一个求解最小吃饼干速度的方法,展示了动态规划和搜索策略的应用。
227

被折叠的 条评论
为什么被折叠?



