Dynamic Programming21 sections · 916 units
Open in Course

Tall Barn - Implementation

The code

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: O(NlogC)O(N \log C) where CC is the range of costs. Space: O(n)O(n) for the DP array.

Time: O(nlogC)O(n \log C). Space: O(n)O(n).