Dynamic Programming21 sections · 916 units
Open in Course

Binary Search - Walkthrough

Finding the right penalty

We want exactly KK elements. Define f(λ)f(\lambda) = optimal count when each element costs +λ+\lambda. ff is monotonically non-increasing in λ\lambda.

More penalty=fewerpenalty = fewer elements used. Binary search: find smallest λ\lambda where f(λ)Kf(\lambda) \leq K. Or find λ\lambda where f(λ)=Kf(\lambda) = K exactly. Subtlety: ff might jump (not hit every value). Handle ties carefully. Often we binary search and check both boundaries.