LeetCode 875. Koko Eating Bananas

原题链接在这里:https://leetcode.com/problems/koko-eating-bananas/

题目:

Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours.

Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour.

Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.

Return the minimum integer K such that she can eat all the bananas within H hours.

Example 1:

Input: piles = [3,6,7,11], H = 8
Output: 4

Example 2:

Input: piles = [30,11,23,4,20], H = 5
Output: 30

Example 3:

Input: piles = [30,11,23,4,20], H = 6
Output: 23

Note:

  • 1 <= piles.length <= 10^4
  • piles.length <= H <= 10^9
  • 1 <= piles[i] <= 10^9

题解:

If H >= piles.length. the worst case is that each hour, koko eats maxPile number of bananas, then she can eat all the bananas.

We could use binary search to try numbers between [1, maxPile].

When trying number mid, for current pile, accumlate how many hours it needs to eat this pile. ceil(pile/mid) = (pile+mid-1)/mid.

When total hours > H, then for each hour, eating mid is not enough, l = mid+1.

Otherwise, total hours <= H, then she could eat all bananas in H hours. Continue trying smaller number.

Time Complexity: O(nlogm). n = piles.length. m = max(piles).

Space: O(1).

AC Java:

 1 class Solution {
 2     public int minEatingSpeed(int[] piles, int H) {
 3         if(piles == null || piles.length > H){
 4             return 0;
 5         }
 6         
 7         int maxPile = 0;
 8         for(int p : piles){
 9             maxPile = Math.max(maxPile, p);
10         }
11         
12         int l = 1;
13         int r = maxPile;
14         while(l<r){
15             int mid = l + (r-l)/2;
16             int cost = 0;
17             for(int p : piles){
18                 cost += (p+mid-1)/mid;
19             }
20             
21             if(cost > H){
22                 l = mid+1;
23             }else{
24                 r = mid;
25             }
26         }
27         
28         return l;
29     }
30 }

 

上一篇:不通过删除重建方式,重置序列值的简单方法


下一篇:Java报jasypt.encryptor.password错误的解决