2.2 Binary Search on Answer
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন
Demo: Koko Eating Bananas — LC 875 (Medium — Amazon/Google High)
Statement (Demo): There are n piles with piles[i] bananas. Every hour Koko eats up to k bananas from one pile (a smaller pile is finished whole). Return the minimum k that lets her finish within h hours.
Example: piles=[3,6,7,11], h=8 → 4 | ⚡ n ≤ 10⁴, 1 ≤ piles[i] ≤ 10⁹, n ≤ h ≤ 10⁹
Approach: Search the answer space, not the array: speed from 1 to max(piles). canFinish(k) is monotonic, so binary search for the smallest feasible k.
function minEatingSpeed(piles, h) {
const canFinish = (k) => piles.reduce((t, p) => t + Math.ceil(p / k), 0) <= h;
let lo = 1,
hi = Math.max(...piles);
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (canFinish(mid))
hi = mid; // try a smaller speed
else lo = mid + 1;
}
return lo;
}
Complexity: Time O(n log max), Space O(1)
নোট · ফাঁকা
প্রবলেম
- Capacity to Ship Packages Within D Daysplan · দিন ০০৯🔥 Must-doLC 1011
Statement: Packages with
weightsmust ship in order on a conveyor belt withindaysdays. Return the minimum belt capacity that makes it possible. The order cannot change.
Example:weights=[1,2,3,4,5,6,7,8,9,10], days=5→15| ⚡n ≤ 5×10⁴,1 ≤ days ≤ n,1 ≤ weights[i] ≤ 500নোট · ফাঁকা