মূল কনটেন্টে যান
🛰️
রিমোট DSA
প্যাটার্নটপিক 2 · Binary Search

2.2 Binary Search on Answer

চিনবেন কীভাবে
"minimize the maximum" / "maximize the minimum", "least speed/capacity/days so that…", the answer lies in a range and feasibility is monotonic (if k works, k+1 works)
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: Koko Eating BananasLC 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=84 | ⚡ 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 · দিন ০১০LC 1011

    Statement: Packages with weights must ship in order on a conveyor belt within days days. 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=515 | ⚡ n ≤ 5×10⁴, 1 ≤ days ≤ n, 1 ≤ weights[i] ≤ 500

    নোট · ফাঁকা