Koko Eating bananas - LeetCode
C++ Code
class Solution {
bool check(int x, vector<int> &piles, int h, int n) {
long long hours = 0;
for(int i=0; i<n; i++) {
if(piles[i]%x == 0) {
hours += piles[i]/x;
} else {
hours += piles[i]/x + 1;
}
}
return (hours <= h);
}
public:
int minEatingSpeed(vector<int>& piles, int h) {
int n = piles.size();
int low = 1;
int high = *max_element(piles.begin(), piles.end());
while(low <= high) {
int mid = low + (high-low)/2;
if(check(mid, piles, h, n)) {
high = --mid;
} else {
low = ++mid;
}
}
return low;
}
};
TypeScript Code
function check(x: number, piles: Array<number>, h: number, n: number): boolean {
let hours: number = 0;
for(let i: number=0; i<n; i++) {
hours += Math.ceil(piles[i]/x);
}
return (hours <= h);
}
function minEatingSpeed(piles: number[], h: number): number {
const n: number = piles.length;
let low: number = 1;
let high: number = Math.max(...piles);
while(low <= high) {
let mid: number = low + Math.floor((high-low)/2);
if(check(mid, piles, h, n)) {
high = --mid;
} else {
low = ++mid;
}
}
return low;
};
Go Code
func check(x int, piles []int, h int, n int) bool {
hours := 0;
for i :=0; i<n; i++ {
hours += piles[i]/x;
if piles[i]%x != 0 {
hours += 1;
}
}
return hours <= h;
}
func minEatingSpeed(piles []int, h int) int {
n := len(piles);
low := 1;
high := math.MinInt32;
for _, val := range piles {
if high < val {
high = val;
}
}
for low <= high {
mid := low + (high-low)/2;
if check(mid, piles, h, n) {
high = mid-1;
} else {
low = mid+1;
}
}
return low;
}