Make array non-decreasing
Given an integer array a, find the minimum total cost to make it non-decreasing, where you may increase or decrease any element by 1 at cost 1 per unit. Return the minimum total cost. Constraints: 1 <= length <= 100000, values fit in normal ints. This is the classic slope-trick / 'make array non-decreasing with min moves' problem solvable with a max-heap, but the array bounds are small enough that an O(n log n) heap solution is required while an O(n^2) DP is too slow at the top.
Implement
min_cost_nondecreasing(a: list[int]) → intExamples
in
[[3,1,2,1]]out3What a strong answer looks like
State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.
0:00 of about 40 min
solution.py
InputExpectedGot
[[3,1,2,1]]3not run yetsample