Dynamic Programming21 sections · 916 units
Open in Course

Sonya - Implementation

Full solution

function solve(a)
    b[i] = a[i] - i for all i
    cost = 0
    maxHeap = empty

    for i from 1 to n:
        push b[i] to maxHeap
        if maxHeap.top() > b[i]:
            cost += maxHeap.top() - b[i]
            pop from maxHeap
            push b[i] to maxHeap

    return cost

Transform aa to bb with bi=aiib_i = a_i - i, then process with a heap. The heap tracks slope-change points.

Time: O(nlogn)O(n \log n). Space: O(n)O(n).