İçeriğe atla
ΣDSA Patterns
Menü
Dil

Cevap Üzerinde İkili Arama

Rehber 3 / 6 · Yol 3 / 6

Interactive

Zihinsel model

Bu problem için animasyonlu çözüm. Adımları kaydır veya boşlukla duraklat; değişmezi yüksek sesle yeniden anlat.

Adım 1 / 8
1F
2F
3F
4T
5T
6T
7T
8T

feasible(x) is monotonic

Search the answer domain, not array indices. Example: min feasible speed.

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

Koko Eating Bananas

Problem (restated)

Koko has piles of bananas and h hours. She eats at speed k bananas/hour (ceil per pile). Find minimum k so she finishes within h hours.

Intuition

Higher k always finishes no later → monotonic. Binary search k in [1, max(pile)].

Approaches

Binary search on eating speed

Tested only
Time O(n log M)Space O(1)

Idea. lo=1, hi=max(piles). feasible(k)=sum(ceil(pile/k)) ≤ h. Find min k.

Walkthrough. piles=[3,6,7,11], h=8 → k=4.

Trade-offs. Must use integer ceil carefully to avoid floats: (pile + k - 1) / k.

Solution
export function minEatingSpeed(piles: number[], h: number): number {
  let lo = 1, hi = Math.max(...piles);
  const feasible = (k: number) => {
    let hours = 0;
    for (const p of piles) hours += Math.ceil(p / k);
    return hours <= h;
  };
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (feasible(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}
export function minEatingSpeed(piles: number[], h: number): number {
  let lo = 1, hi = Math.max(...piles);
  const feasible = (k: number) => {
    let hours = 0;
    for (const p of piles) hours += Math.ceil(p / k);
    return hours <= h;
  };
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (feasible(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}

Template connection

Binary search on answer with a linear feasibility check.

Reflection