华为OD机试E卷-爱吃蟠桃的孙悟空(100分) JAVA
输入样例:
输入样例1:
2 3 4 5 4
5
输出:5
输入样例2:
2 3 4 5
3
输出:0
输入样例3:
30 11 23 4 20
6
输出:23
代码实例:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] peaches = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int hours = in.nextInt();
System.out.println(min_eating_speed(peaches, hours));
}
private static int min_eating_speed(int[] peaches, int hours) {
//计算吃完所有桃子的最小速度
if (peaches.length > hours) {
return 0;
}
int left = 1, right = Arrays.stream(peaches).max().getAsInt();
while (left < right) {
int mid = (left + right) / 2;
if (can_eat_all(mid, peaches, hours)) {
//如果在mid时间能吃完的话,说明还能把吃桃的速度放慢,即把right左移置为mid
right = mid;
} else left = mid + 1; //吃不完的话,说明要把吃桃的速度放快点。即把left右移置为mid
}
return left;
}
private static boolean can_eat_all(int mid, int[] peaches, int hours) {
//检查是否能在给定的时间用mid的速度吃完桃子
int time = 0;
for (int i = 0; i < peaches.length; i++) {
if (peaches[i] % mid > 0) {
time++;
}
time += peaches[i] / mid;
}
return time <= hours;
}
