#K77657. Minimum Operations to Make Pillars Non-decreasing

    ID: 34913 Type: Default 1000ms 256MiB

Minimum Operations to Make Pillars Non-decreasing

Minimum Operations to Make Pillars Non-decreasing

You are given N pillars with initial heights. In one operation, you can increase the height of a pillar. The goal is to make the sequence of pillar heights non-decreasing (i.e. each height is at least as large as the previous one).

Formally, given an array \( h_1, h_2, \dots, h_N \), you want \( h_1 \le h_2 \le \dots \le h_N \). If for some index \( i \) (with \( 2 \le i \le N \)) we have \( h_i < h_{i-1} \), you need to perform \( h_{i-1} - h_i \) operations to raise \( h_i \) to \( h_{i-1} \). The task is to compute the minimum total number of operations required to achieve a non-decreasing sequence.

Input Constraints: The number of pillars \( N \) and their heights are provided. It is guaranteed that \( 1 \le N \le 10^5 \) and each height is a non-negative integer.

inputFormat

The input is read from stdin and contains two lines.

  • The first line contains a single integer \( N \), the number of pillars.
  • The second line contains \( N \) space-separated integers representing the heights of the pillars.

outputFormat

Output the minimum number of operations required to transform the array into a non-decreasing sequence. The result should be written to stdout as a single integer.

## sample
5
3 1 4 2 5
4