Code Room
CodingHardcod-g723
Subject Slope trickLevel Senior–Staff~40 minCommon in Algorithms & data structures interviewsIndustries Software development

Question

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]) → int
Examples
in[[3,1,2,1]]out3
What 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.

Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.

Run or narrate your approach, then ask the coach.