WCC '25 P4 - Santa's Stocking Order
Santa is delivering candy stockings to houses along a straight Christmas street. The houses are numbered from \(1\) to \(N\), from west to east.
Each house \(i\) currently as \(a_i\) stockings hanging. To make the street look neat for the Christmas parade, Santa wants the number of stockings to be non-decreasing from left to right:
\(a_1 \le a_2 \le \dots \le a_N\)
However, the current arrangement might not satisfy this. Santa can perform the following operations:
- Add one stocking to any house (costs \(1\) effort)
- Remove one stocking from any house (also costs \(1\) effort)
Santa may perform any number of these operations. Your task is to compute the minimum total effort required to make the sequence non-decreasing.

Image: Santa and his sleigh
Constraints
\(1 \le N \le 2\times10^{5}\)
\(0 \le a_i \le 10^{9}\)
Input Specification
The first line contains an integer \(N\).
The second line contains \(N\) integers: \(a_1, a_2, \dots, a_N\)
The following table shows how the available 7 marks are distributed:
| Marks | Additional Constraints |
|---|---|
| 1 | \(N \le 1000\) |
| 2 | \(N \le 5000\) |
| 2 | Sequence already almost sorted |
| 2 | None |
Output Specification
Output the result of evaluating the expression.
Sample Input 1
4
2 2 1 3
Sample Output 1
1
Explanation for Sample Output 1
We only need to increase the third house from \(1 \rightarrow 2\) (\(cost = 1\)), resulting in:
2 2 2 3
which is non-decreasing.
Sample Input 2
5
5 4 3 2 1
Sample Output 2
6
Explanation for Sample Output 2
One optimal result would be to transform the array to \(3, 3, 3, 3, 3\)
\(cost = |5-3| + |4-3| + |3-3| + |2-3| + |1-3|\)
\(cost = 2 + 1 + 0 + 1 + 2 = 6\)
Comments