Took me a while to realize this reduces to looking at the difference array.
Reframe the problem as finding the minimum total increments to make the array non-decreasing, where each increment operation adds a positive value to a contiguous subarray. Recognize that the optimal strategy is to increment each element just enough to match the previous element, and the total cost equals the sum of positive differences between consecutive elements. Present a greedy algorithm that scans the array once, accumulating the required increments.
Pro tip: Clarify that the increments must be positive integers, but the total sum is what matters; the greedy approach works because any increment to a later element can be shifted to earlier elements without increasing cost, and the minimum cost is exactly the sum of positive differences.
Restate the problem: we can add a positive integer to any subarray, and we want the minimum total sum of added values to make the array non-decreasing. Note that the array elements are integers, and the added values are positive integers.
Observe that to make the array non-decreasing, each element must be at least as large as the previous one. The minimal total increments can be achieved by only increasing elements that are smaller than their predecessor, and the amount needed is the difference.
The minimum total sum of added values is the sum over all i from 1 to n-1 of max(0, a[i-1] - a[i]). This is because each such difference must be compensated by increments, and increments can be applied independently to each element without affecting others.
Test the formula on simple cases: e.g., [3,2,1] requires increments of 1 and 1 (total 2) to become [3,3,3]; [1,2,3] requires 0; [5,1,1] requires 4 and 4 (total 8) to become [5,5,5]. Confirm that the sum of positive differences matches.
The algorithm runs in O(n) time and O(1) space. Edge cases include already non-decreasing arrays (cost 0), strictly decreasing arrays, and arrays with negative numbers (the formula still holds).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.