875. Koko Eating Bananas

刺骨的言语ヽ痛彻心扉 2023-07-06 14:45 53阅读 0赞

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:

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

Example 2:

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

Example 3:

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

Note:

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

解法:二分法

  1. class Solution {
  2. public:
  3. int canEat(vector<int>& piles, int k)
  4. {
  5. int sum = 0;
  6. for(int i = 0; i < piles.size();i++)
  7. {
  8. sum += ceil((double)piles[i] / k);
  9. }
  10. return sum;
  11. }
  12. int minEatingSpeed(vector<int>& piles, int H)
  13. {
  14. int low = 1;
  15. int high = pow(10, 9);
  16. while (low < high)
  17. {
  18. int mid = low + (high - low) / 2;
  19. if (canEat(piles, mid) <= H)
  20. {
  21. high = mid;
  22. }
  23. else
  24. {
  25. low = mid + 1;
  26. }
  27. }
  28. return low;
  29. }
  30. };

发表评论

表情:
评论列表 (有 0 条评论,53人围观)

还没有评论,来说两句吧...

相关阅读

    相关 CF558 A. Eating Soup

      给出结点数n  结点两两相连成一个环     再给出m   求 在环中去掉m个点   使得联通块最大   输出最大联通块   比赛的时候我还在模拟。。。 其实可以找一