LeetCode 875. Koko Eating Bananas
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于LeetCode 875. Koko Eating Bananas的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Koko Eating Bananas 科科吃香蕉