Make array non-decreasing

Write codeHard40 min

Your task

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.

Examples

min_cost_nondecreasing(a: list[int]) -> int
Example 1
Inputmin_cost_nondecreasing([3, 1, 2, 1])
Output3