jayati

Koko Eating Bananas

Mar 8th, 2023
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     long long getHoursToEatAll(vector<int>&piles, int bananasPerHour)
  4.     {
  5.         long long totalHours = 0;
  6.         for (int i = 0; i < piles.size(); i++)
  7.         {
  8.             int hoursToEatPile = ceil(piles[i] / (double)bananasPerHour);
  9.             totalHours += hoursToEatPile;
  10.         }
  11.         return totalHours;
  12.     }
  13.     int minEatingSpeed(vector<int>& piles, int targetHours)
  14.     {
  15.         int low = 1, high = *(max_element(piles.begin(), piles.end()));
  16.         int ans = -1;
  17.         //================================================================
  18.         while(low <= high)
  19.         {
  20.             int mid = low + (high - low) / 2;
  21.             long long hoursToEatAll = getHoursToEatAll(piles, mid);
  22.            
  23.             if (hoursToEatAll <= targetHours)
  24.             {
  25.                 ans = mid; //record the answer (this is the best we could record till curr step)
  26.                 high = mid - 1;
  27.             }
  28.             else low = mid + 1;
  29.            
  30.         }
  31.         //=================================================================
  32.         return ans;
  33.     }
  34. };
Advertisement
Add Comment
Please, Sign In to add comment