Problem:
Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.

Solution in Java (OpenJDK 11.0.6) (judge verdict: Time Limit Exceeded)

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner scan = new Scanner(System.in);
		
		long total = 0;
		
		int n = scan.nextInt();
		long[] a = new long[n];
		
		long tall = 0;
		int x = -1;
		int same = 1;
		
		for(int i = 0; i < n; i++) {
			a[i] = scan.nextLong();
			
			if(tall < a[i]) {
				tall = a[i];
				x = i;
				
			}
			else if(tall == a[i]) {
				same++;
			}
		}
		
		if(same == n) {
			System.out.print(0);
			return;
		}
		if(x == n-1) {
			System.out.print(0);
			return;
		}
		if(x == 0) {
			for(int i = 0; i < n; i++) {
				total += tall - a[i];
			}
			System.out.print(total);
			return;
		}
		if(x == n-2) {
			total += tall - a[n-1];
			n = x;
		}
		
		while(true) {
			long big = 0;
			int index = 0;
			int same1 = 1;
			for(int i = 0; i < n; i++) {
				if(big < a[i]) {
					big = a[i];
					index = i;
				}
				else if(big == a[i]) {
					same1++;
				}
			}
			if(same1 == n) {
				n = index;
				if( index == 0 && n == 0) {
					break;
				}
				continue;
			}
			for( int i = index; i < n; i++) {
				total += big - a[i];
			}
			n = index;
			
			if( index == 0 && n == 0) {
				break;
			}
		}
		System.out.print(total);
	}

}