#K65882. Minimum Cost to Equalize Array
Minimum Cost to Equalize Array
Minimum Cost to Equalize Array
You are given an array of n integers. Your goal is to make all elements of the array equal using the following operations:
- You can increase a chosen contiguous segment of the array by 1 at a cost of 1 unit per increment.
- You can decrease a chosen contiguous segment by any amount with no cost.
It can be proven that the minimum cost to equalize the array is given by:
\[ \text{cost} = \sum_{i=1}^{n-1} \max(0, a_{i+1} - a_{i}) \]In other words, iterate through the array from left to right; whenever you encounter an increase, add the difference to the cost. Your task is to compute and output this minimum cost.
inputFormat
The first line of input contains a single integer n (1 ≤ n ≤ 105), the number of elements in the array.
The second line contains n space-separated integers representing the array.
outputFormat
Output a single integer, the minimum cost needed to make all elements of the array equal.
## sample5
1 2 3 2 1
2