Here's
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
else
hi := mid
(cost, count) := computeWithPenalty(a, lo)
return cost - lo * K
function computeWithPenalty(a, lambda)
totalCost := 0, totalCount := 0
for 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: .