# Koko Eating Bananas in C++

C++Server Side ProgrammingProgramming

Suppose we have N piles of bananas, the i-th pile has piles[i] bananas. Here the guards have gone and will come back in H hours. Koko can decide her bananas-per-hour eating speed is K. Each hour, she takes some pile of bananas, and eats K bananas from that pile. If the pile has less than K bananas, then she consumes all of them instead, and won't eat any more bananas during this hour. Consider Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back. We have to find the minimum integer K such that she can eat all the bananas within H hours.

So if the input is like [3,6,7,11], and H = 8, then the output will be 4.

To solve this, we will follow these steps −

• Define a method called ok(), this will take array a, two values x and h

• time := 0

• for i in range 0 to size of a

• time := time + a[i] / x

• time := time + i when a[i] mod x is 0

• return true when time <= H

• From the main method do the following

• n := size of the piles array, set sum := 0, low := 1, high := 0

• for i in range 0 to n – 1

• high := max of piles[i] and high

• while low < high

• mid := low + (high – low ) /2

• if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1

• if ok(piles, mid, H) is true, then set high := mid, otherwise low := mid + 1

• return high

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
bool ok(vector <int>& a, int x, int H){
int time = 0;
for(int i = 0; i < a.size(); i++){
time += a[i] / x;
time += (a[i] % x ? 1 : 0);
}
return time <= H;
}
int minEatingSpeed(vector<int>& piles, int H) {
int n = piles.size();
lli low = 1;
lli sum = 0;
lli high = 0;
for(int i = 0; i < n; i++)high = max((lli)piles[i], high);
while(low < high){
int mid = low + (high - low) / 2;
if(ok(piles, mid, H)){
high = mid;
}else{
low = mid + 1;
}
}
return high;
}
};
main(){
vector<int> v = {3,6,7,11};
Solution ob;
cout << (ob.minEatingSpeed(v, 8));
}

### Input

[3,6,7,11]
8

## Output

4
Published on 10-Apr-2020 09:37:15
Advertisements