I am trying to solve the Koko Eating Bananas problem using binary search, but I want to confirm whether my approach and logic are correct and optimized.
Problem statement (brief):
Given an array arr[] where each element represents a pile of bananas, and an integer k representing total hours, Koko can eat from only one pile per hour at a fixed speed s (bananas/hour).
The task is to find the minimum value of s such that all bananas can be eaten within k hours.
My Approach
Minimum possible speed = 1
Maximum possible speed = max(arr)
Use binary search on the speed
For a given speed mid, calculate total hours using
ceil(arr[i] / mid)
If total hours ≤ k, try a smaller speed
Code (HTML + JavaScript)
Copy code
Html
function calculateSpeed(arr, k) {
let low = 1;
let high = Math.max(...arr);
let ans = high;
while (low \<= high) {
let mid = Math.floor((low + high) / 2);
let hours = 0;
for (let bananas of arr) {
hours += Math.ceil(bananas / mid);
}
if (hours \<= k) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
console.log(calculateSpeed([5,10,3], 4)); // Expected output: 5
My Questions
Is binary search the correct approach for this problem?
Is my time complexity optimal for large inputs?
Are there any edge cases or improvements I should consider?
Any feedback or corrections would be appreciated.
Thanks in advance!