Here's
plaintext function solve(a, K) // Binary search on lambda lo := 0, hi := max(a) while hi - lo > epsilon mid := (lo + hi) / 2 (cost, count) := computeWithPenalty(a, mid) if count > K lo := mid // Need higher penalty to use fewer cows else hi := mid (cost, count) := computeWithPenalty(a, lo) return cost - lo * K function computeWithPenalty(a, lambda) totalCost := 0, totalCount := 0 Each floor i c := optimal cows for floor i with penalty lambda totalCost += a[i] / c + lambda * c totalCount += c return (totalCost, totalCount)
Time: where is the range of costs. Space: for the DP array.
Time: . Space: .