jiahuimbzuai/CoQuIR huggingface dataset:
//  [swift]
import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let N = Int(input[0])!
let M = Int(input[1])!

var cnt = Array(count: M, repeatedValue: 0)

for _ in 0 ..< N {
    let input = readLine()!.componentsSeparatedByString(" ")
    let K = Int(input[0])!
    for i in 0 ..< K {
        let A = Int(input[i+1])!
        cnt[i] = A
    }
}

var ans = 0
for i in 0 ..< M {
    if cnt[i] == N {
        ans += 1
    }
}

print(ans)
//  [swift]
import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let N = Int(input[0])!
let M = Int(input[1])!

var cnt = Array(count: M, repeatedValue: 0)

for _ in 0 ..< N {
    let input = readLine()!.componentsSeparatedByString(" ")
    let K = Int(input[0])!
    for i in 0 ..< K {
        let A = Int(input[i])!
        cnt[i] = A
    }
}

var ans = 0
for i in 0 ..< M {
    if cnt[i] == N {
        ans += 1
    }
}

print(ans)
//  [swift]
import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let N = Int(input[0])!
let M = Int(input[1])!

var cnt = Array(count: M, repeatingValue: 0)

for _ in 0 ..< N {
    let input = readLine()!.componentsSeparatedByString(" ")
    let K = Int(input[0])!
    for i in 0 ..< K {
        let A = Int(input[i])!
        cnt[i] = A
    }
}

var ans = 0
for i in 0 ..< M {
    if cnt[i] == N {
        ans += 1
    }
}

print(ans)
//  [typescript]
const main = (input) => {
  const lines = input.trim().split("\n");
  const [N, M] = lines[0].split(' ').map(x => parseInt(x));
  const A = [].concat(...lines.slice(1).map(line => line.split(' ').slice(1))).map(food => parseInt(food) - 1);

  const countMap = Array(M).fill(0);
  A.forEach(food => countMap[food]++);
  const ans = countMap.filter(count => count === N).length

  console.log(ans)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
const t={input:require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/),n:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.n())}return a}else{const a=t.input[0];t.input.shift();return Number(a)}},s:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.s())}return a}else{const a=t.input[0];t.input.shift();return String(a)}},c:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.c())}return a}else{let a=t.input[0].split('');const b=a[0];a.shift();if(a.length>0){t.input[0]=a.join('')}else{t.input.shift()}return String(b)}},o:(...arg)=>{console.log(...arg)},abs:(a)=>{return Math.abs(a)},min:(...a)=>{return Math.min(...a)},max:(...a)=>{return Math.max(...a)},floor:(a)=>{return Math.floor(a)},asc:(ar:number[])=>{return ar.sort((a,b)=>{return a-b})},desc:(ar:number[])=>{return ar.sort((a,b)=>{return b-a})},sw:(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;i+=2){if(eval(a+op+arr[i]))return arr[i+1];}return arr[arr.length-1]}};
const main=()=>{
  let n=t.n()
  let nr=new Array(t.n())
  nr.fill(0)
  for(let i=0;i<n;i++){
    let jl=t.n()
    for(let j=0;j<jl;j++){
      nr[t.n()-1]++
    }
  }
  let ans=0
  for(let i=0;i<nr.length;i++){
    if(nr[i]==n)ans++
  }
  t.o(ans)
}
main()
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')
 
const [head, ...rest] = stdin.split('\n').filter(e=>e)
 
const [n, m] = head.split(' ').map(Number)
 
const ka = rest.map(e=>e.split(' ').map(Number))
 
let commons = []
 
ka.forEach((e,i)=>{
  const [k, ...a] = e
  
  if(i === 0){
    commons = a
  } else {
    const filtered = a.filter(v => {
      return commons.indexOf(v) > -1
    })
 
    commons = filtered
  }
})
 
console.log(commons.length)
//  [typescript]
const main = (input) => {
  const lines = input.trim().split("\n");
  const [N, M] = lines[0].split(' ').map(x => parseInt(x));
  const A = lines.slice(1).flatMap(line => line.split(' ').slice(1).map(food => parseInt(food) - 1));

  const countMap = Array(M).fill(0);
  A.forEach(food => countMap[food]++);
  const ans = countMap.filter(count => count === N).length

  console.log(ans)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
const main = (input: string) => {
  const lines = input.split("\n").slice(1);
  let K = [];
  let result = 0;

  for (let i = 0; i < lines.length; i++) {
    K.push(lines[i].split(" ").map(str => parseInt(str)))
    K[i].shift();
  }
  
  for (let i = 0; i < K.length; i++) {
    let answer = 0;

    for (let j = 0; j < K[i].length; j++) {
      if(K[i].indexOf(K[i][j]) >= 0) {
        answer += 1;
      }
    }

    if(answer === K.length) {
      result += 1;
    }
  }

  if(K.length === 1) {
    result = K[0].length;
  }

  console.log(result)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
const main = (input: string) => {
  const lines = input.split("\n").slice(1);
  let K = [];
  let result = 0;

  for (let i = 0; i < lines.length; i++) {
    K.push(lines[i].split(" ").map(str => parseInt(str)))
    K[i].shift();
  }
  
  for (let i = 0; i < K.length; i++) {
    let answer = 0;

    for (let j = 0; j < K[i].length; j++) {
      if(K[i].indexOf(K[i][j]) >= 0) {
        answer += 1;
      }
    }

    if(answer === K.length) {
      result += 1;
    }

    if(K.length === 1) {
      result = K[0].length;
    }
  }

  console.log(result)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [python]
def main():
    _ = input()
    a = list(map(int, input().split()))
    max_height = 0
    ans = 0
    for height in a:
        if max_height <= height:
            max_height = height
        else:
            ans += max_height - height
    print(ans)

if __name__ == "__main__":
    main()
//  [python]
def probC():
    N = input()
    A = map(int, input().split())

    step = 0
    max_height = 0
    for i in A:
        if max_height < i:
            max_height = i
        else:
            step += max_height - i

    print(step)


def main():
    probC()


if __name__ == '__main__':
    main()
//  [python]
def main():
    N = int(input())
    A = list(map(int, input().split()))

    tallest = A[0]
    ans = 0

    for height in A:
        if height < tallest:
            ans += tallest - height
        elif height > tallest:
            tallest = height

    print(ans)


if __name__ == "__main__":
    main()
//  [python]
N=int(input())
A=list(map(int,input().split()))
a=0
s=[]
for i in A:
  if i<a:
    s.append(a-i)
    print(s)
  else:
    a=i
print(sum(s))
//  [python]
N=int(input())
A=list(map(int,input().split()))
a=0
s=[]
for i in A:
  if i<a:
    s.append(a-i)
    a=i
  else:
    a=i
print(sum(s))
//  [python]
N=int(input())
A=list(map(int,input().split()))
a=0
s=[]
for i in A:
  if i<a:
    s.append(i-a)
    a=i
  else:
    a=i
print(sum(s))
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
        FastScanner sc = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        int n=sc.nextInt();
        int a[]=sc.readArray(n);
        int max=a[0];
        int sum=0;
        for (int i=1;i<n;i++){
            max=Math.max(a[i],max);
            sum+=max-a[i];


        }
        System.out.println(sum);

        out.flush();

    }









    static void sort(int[] a) {
        ArrayList<Integer> l=new ArrayList<>();
        for (int i:a) l.add(i);
        Collections.sort(l);
        for (int i=0; i<a.length; i++) a[i]=l.get(i);
    }
    static void sortReverse(long[] a) {
        ArrayList<Long> l=new ArrayList<>();
        for (long i:a) l.add(i);
//        Collections.sort.(l);
        Collections.sort(l,Collections.reverseOrder());
        for (int i=0; i<a.length; i++) a[i]=l.get(i);
    }

    static class FastScanner {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer("");
        String next() {
            while (!st.hasMoreTokens())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
        int[] readArray(int n) {
            int[] a=new int[n];
            for (int i=0; i<n; i++) a[i]=nextInt();
            return a;
        }
        long[] readArrayLong(long n) {
            long[] a=new long[(int)n];
            for (int i=0; i<n; i++) a[i]=nextLong();
            return a;
        }
        long nextLong() {
            return Long.parseLong(next());
        }
    }


}
//  [java]
import java.util.*;
import java.io.*;
import java.lang.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int[] arr = new int[n];

        int ans = 0;

        for (int i = 0; i<n; i++){
            arr[i] = sc.nextInt();
        }

        for (int i = 1; i<n; i++){
            if (arr[i] < arr[i-1]){
                ans += (arr[i-1]-arr[i]);
                arr[i] = arr[i-1];
            }
        }
        System.out.println(ans);
    }
}
//  [java]
import java.util.*;
import java.io.*;
import java.lang.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int[] arr = new int[n];

        int ans = 0;

        for (int i = 0; i<n; i++){
            arr[i] = sc.nextInt();
        }

        for (int i = 1; i<n; i++){
            if (arr[i] < arr[i-1]){
                ans = ans + (arr[i-1]-arr[i]);
                arr[i] = arr[i-1];
            }
        }
        System.out.println(ans);
    }
}
//  [cpp]
#pragma GCC optimize ("O2")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	if ((tmp & ma0) ^ ma0) {
		int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
		tmp = tmp << dig & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += (72 - dig >> 3);
	}
	else {
		tmp = tmp & ma1;
		tmp = tmp * 10 + (tmp >> 8) & ma2;
		tmp = tmp * 100 + (tmp >> 16) & ma3;
		tmp = tmp * 10000 + (tmp >> 32) & ma4;
		ci += 8;
		if ((ct = *ci++) >= '0') {
			tmp = tmp * 10 + ct - '0';
			if (*ci++ == '0') {
				tmp = tmp * 10;
				ci++;
			}
		}
	}
	return tmp;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint();
	int saidai = 0;
	ll kotae = 0;
	rep(i, N) {
		int a = getint();
		if (saidai < a) {
			saidai = a;
		}
		else {
			kotae += saidai - a;
		}
	}
	printf("%lld\n", kotae);

	Would you please return 0;
}
//  [cpp]
#pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
template<class S, class T> inline S max_L(S a,T b){
  return a>=b?a:b;
}
inline int my_getchar_unlocked(){
  static char buf[1048576];
  static int s = 1048576;
  static int e = 1048576;
  if(s == e && e == 1048576){
    e = fread_unlocked(buf, 1, 1048576, stdin);
    s = 0;
  }
  if(s == e){
    return EOF;
  }
  return buf[s++];
}
inline void rd(int &x){
  int k;
  int m=0;
  x=0;
  for(;;){
    k = my_getchar_unlocked();
    if(k=='-'){
      m=1;
      break;
    }
    if('0'<=k&&k<='9'){
      x=k-'0';
      break;
    }
  }
  for(;;){
    k = my_getchar_unlocked();
    if(k<'0'||k>'9'){
      break;
    }
    x=x*10+k-'0';
  }
  if(m){
    x=-x;
  }
}
struct MY_WRITER{
  char buf[1048576];
  int s;
  int e;
  MY_WRITER(){
    s = 0;
    e = 1048576;
  }
  ~MY_WRITER(){
    if(s){
      fwrite_unlocked(buf, 1, s, stdout);
    }
  }
}
;
MY_WRITER MY_WRITER_VAR;
void my_putchar_unlocked(int a){
  if(MY_WRITER_VAR.s == MY_WRITER_VAR.e){
    fwrite_unlocked(MY_WRITER_VAR.buf, 1, MY_WRITER_VAR.s, stdout);
    MY_WRITER_VAR.s = 0;
  }
  MY_WRITER_VAR.buf[MY_WRITER_VAR.s++] = a;
}
inline void wt_L(char a){
  my_putchar_unlocked(a);
}
inline void wt_L(long long x){
  int s=0;
  int m=0;
  char f[20];
  if(x<0){
    m=1;
    x=-x;
  }
  while(x){
    f[s++]=x%10;
    x/=10;
  }
  if(!s){
    f[s++]=0;
  }
  if(m){
    my_putchar_unlocked('-');
  }
  while(s--){
    my_putchar_unlocked(f[s]+'0');
  }
}
template<class S, class T> inline S chmax(S &a, T b){
  if(a<b){
    a=b;
  }
  return a;
}
int N;
int A[200000];
int main(){
  int i;
  long long res = 0;
  long long mx = -1;
  rd(N);
  {
    int Lj4PdHRW;
    for(Lj4PdHRW=(0);Lj4PdHRW<(N);Lj4PdHRW++){
      rd(A[Lj4PdHRW]);
    }
  }
  for(i=(0);i<(N);i++){
    res +=max_L(mx - A[i], 0);
    chmax(mx, A[i]);
  }
  wt_L(res);
  wt_L('\n');
  return 0;
}
// cLay varsion 20200813-1 [beta]

// --- original code ---
// int N, A[2d5];
// {
//   ll res = 0, mx = -1;
//   rd(N,A(N));
//   rep(i,N){
//     res += max(mx - A[i], 0);
//     mx >?= A[i];
//   }
//   wt(res);
// }
//  [cpp]
#include<cstdio>
//#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int maxv = 200005;
const int inf = 1e9 + 7;
int ar[maxv];
int main(){
	//freopen("data.in","r",stdin);
	//freopen("abc176c.out","w",stdout);
	int n;
	scanf("%d",&n);
	ll ans=0;
	for(int i=0;i<n;i++){
		scanf("%d",&ar[i]);
		if(i>0&&ar[i]-ar[i-1]<0){
			ans+=(ar[i-1]-ar[i]);
			ans%=inf;
			ar[i]=ar[i-1];
		}
	}
	printf("%lld\n",ans);
	return 0;
}
//  [cpp]
#include<cstdio>
//#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int maxv = 200005;
const int inf = 1e9 + 7;
int ar[maxv];
int main(){
	//freopen("data.in","r",stdin);
	//freopen("abc176c.out","w",stdout);
	int n;
	scanf("%d",&n);
	ll ans=0;
	for(int i=0;i<n;i++){
		scanf("%d",&ar[i]);
		if(i>0&&ar[i]-ar[i-1]<0){
			ans+=(ar[i-1]-ar[i]);
			ans%=inf;
			ar[i]=ar[i-1];
		}
	}
	printf("%d\n",ans);
	return 0;
}
//  [cpp]
#include<cstdio>
//#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int maxv = 200005;
const int inf = 1e9 + 7;
int ar[maxv];
int main(){
	//freopen("data.in","r",stdin);
	//freopen("abc176c.out","w",stdout);
	int n;
	scanf("%d",&n);
	int ans=0;
	for(int i=0;i<n;i++){
		scanf("%d",&ar[i]);
		if(i>0&&ar[i]-ar[i-1]<0){
			ans+=(ar[i-1]-ar[i]);
			ar[i]=ar[i-1];
		}
	}
	printf("%d\n",ans);
	return 0;
}
//  [c]
#include <stdio.h>

int read()
{
	char c;
	while((c = getchar()) < 48 || c > 57);
	int x = c - 48;
	while((c = getchar()) > 47 && c < 58) x = x * 10 + c - 48;
	return x;
}


int main()
{	 
	int n, m, x, i;
	long long ans = 0;	
	
	n = read();
	m = read();
	for(i = 1; i < n; i++){
		x = read();
		if(x >= m) m = x;
		else ans += m - x;
	}
	printf("%lld\n", ans);
		
	return 0;
}
//  [c]
#include <ctype.h>
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")

#define getchar getchar_unlocked
#define putchar putchar_unlocked
int32_t nextint(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); bool s=false; if(c=='-'){s=true;c=getchar();} uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
int64_t nextlong(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); int s=0; if(c=='-'){s=1;c=getchar();} uint64_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }
void rsorta_d32(void *base, const int count, const int size, const int index){
	typedef int32_t rsort_t;
	rsort_t (*a)[size] = (rsort_t(*)[size])base;
	rsort_t (*b)[size] = (rsort_t(*)[size])malloc(count*size*sizeof(rsort_t));
	int c[0x100];
	for(int k=0; k<4; k++){
		memset(c, 0, sizeof(c)); for(int i=0; i<count; i++){ c[(a[i][index]>>(k<<3))&0xFF]++; } for(int i=1; i<0x100; i++) c[i]+=c[i-1]; for(int i=count-1; i>=0; i--){ int to=--c[(a[i][index]>>(k<<3))&0xFF]; for(int j=0; j<size; j++){ b[to][j]=a[i][j]; } }{rsort_t(*t)[size]=a; a=b; b=t;}
	}
	free(b);
}

int a[200000];
int main(void){
	int n=nextint();
	for(int i=0; i<n; i++){
		a[i]=nextint();
	}
	int h=a[0];
	long ans=0;
	for(int i=1; i<n; i++){
		if(a[i]>h){
			h=a[i];
		}else{
			ans+=h-a[i];
		}
	}
	printf("%ld\n", ans);
}
//  [c]
#include<stdio.h>
#include<stdlib.h>

int main(){
    int N;
    scanf("%d%*c",&N);
    char *s = (char *)malloc(11 * N * sizeof(char));
    char *ms = s;
    fgets(s,11*N,stdin);
    unsigned long int max = 0;
    unsigned long int sum = 0;
    for(int i = 0;i < N; i++){
        int n;
        unsigned long int a;
        int j = 0;
        for(j = 0; j < 11; j++){
            if(s[j] == ' '){
                
                s[j] = '\0';
                break;
            }
        }
        a = (unsigned long int)atoi(s);
        if(max > a){
            sum += max - a;
        }else
        {
            max = a;
        }
        if(i<N-1)
        s = &s[j+1];
    }
    free(ms);
    printf("%ld\n",sum);
    return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
int	max(int a, int b)
{
	return ((a > b) ? a : b);
}
int	main(void)
{
	int	N;
	int	*A;
	int	res = 0;
	int	m = 0;
	int	i;

	scanf("%d", &N);
	A = malloc(sizeof(int) * N);
	for (i = 0; i < N; i++)
		scanf("%d", &A[i]);
	for (i = 0; i < N; i++)
	{
		m = max(m, A[i]);
		res += m - A[i];
	}
	printf("%lld\n", res);
	free(A);
	return (0);
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int	main(void)
{
	int	N;
	int	*A, *B;
	long	res = 0;
	int	m;
	int	i;

	scanf("%d", &N);
	A = malloc(sizeof(int) * N);
	for (i = 0; i < N; i++)
		scanf("%d", &A[i]);
	m = A[0];
	B = malloc(sizeof(int) * (N - 1));
	for (i = 0; i < N - 1; i++)
	{
		if (m > A[i + 1])
			B[i] = m - A[i + 1];
		else
		{
			m = A[i + 1];
			B[i] = 0;
		}
	}
	for (i = 0; i < N - 1; i++)
		res += B[i];
	printf("%d\n", res);
	free(A);
	free(B);
	return (0);
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int	main(void)
{
	int	N;
	int	*A, *B;
	int	res = 0;
	int	m;
	int	i;

	scanf("%d", &N);
	A = malloc(sizeof(int) * N);
	for (i = 0; i < N; i++)
		scanf("%d", &A[i]);
	m = A[0];
	B = malloc(sizeof(int) * (N - 1));
	for (i = 0; i < N - 1; i++)
	{
		if (m > A[i + 1])
			B[i] = m - A[i + 1];
		else
		{
			m = A[i + 1];
			B[i] = 0;
		}
	}
	for (i = 0; i < N - 1; i++)
		res += B[i];
	printf("%d\n", res);
	free(A);
	free(B);
	return (0);
}
//  [javascript]
function Main(input) {
	const col = input.split("\n");
	const N = parseInt(col[0], 10);
	let row = col[1].split(" ");
	for(let s=0; s < row.length; s++){
		row[s] = parseInt(row[s], 10);
	}
	let tmp = row[0];
	let cnt = 0;
	if(row.length > 1){
		for(let i = 1; i < row.length; i++){
			if(tmp > row[i]){
				cnt += tmp - row[i];
			} else {
				tmp = row[i];
			}
		}
	}
	console.log(cnt);
};

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	const inputLines = input.split("\n");
	const line0 = inputLines[0];
	const line0vars = line0.split(" ");
	const line1 = inputLines[1];
	const line1vars = line1.split(" ");

	const n = parseInt(line0vars[0], 10);

	var result = 0;
	var current = 0;

	for (var i = 0; i < n; i++) {
		const a = parseInt(line1vars[i], 10);
		if (i === 0) {
			current = a;
			continue;
		}
		if (current < a) {
			current = a;
		} {
			result += current - a;
		}
	}

	console.log(result);

	
	// tmp = input[1].split(" ");
	// //文字列から10進数に変換するときはparseIntを使います
	// var a = parseInt(input[0], 10);
	// var b = parseInt(tmp[0], 10);
	// var c = parseInt(tmp[1], 10);
	// var s = input[2];

	//出力
	// console.log('%d %s',a+b+c,s);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

// node index.js
// 1
// 2 3
// test
// (Ctrl + D)
//  [javascript]
function main(lines) {
  const N = n();
  const as = na();
  
  let max = as[0];
  let ans = 0;
  for (let i = 0; i < N; i++) {
    ans += Math.max(max-as[i], 0);
    max = Math.max(max, as[i]);
  }
  
  return ans;
}



const lines = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");

let lineCount = 0;
const s = () => lines[lineCount++];
const n = () => Number(s());
const b = () => BigInt(s());
const sa = () => s().split(' ');
const na = () => sa().map(Number);
const ba = () => sa().map(BigInt);

const ans = main(lines);
console.log( ans );
//  [javascript]
function Main(input){
    // 入力値取得
    input = input.split("\n");
    tmp = input[1].split(" ");
    var people = input[0];
    var diff = 0;
    var dai = 0;

    // tmpの数字をループして
    for (var i = 0; i <= people; i++) {
      if((tmp[i+1] - tmp[i]) > 0) {
        diff = tmp[i+1] - tmp[i]
        dai = dai + Math.abs(diff)
      } else {
        dai = dai
      }
    }
    console.log(dai);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
    // 入力値取得
    input = input.split("\n");
    tmp = input[1].split(" ");
    var people = input[0];
    var diff = 0;
    var dai = 0;

    // tmpの数字をループして
    for (var i = 0; i <= people; i++) {
      if((tmp[i+1] - tmp[i]) >= 0) {
        diff = tmp[i+1] - tmp[i]
        dai = dai + Math.abs(diff)
      }
    }
    console.log(dai);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
    // 入力値取得
    input = input.split("\n");
    tmp = input[1].split(" ");
    var people = input[0];
    var result = 0;
    var dai = 0;

    // tmpの数字をループして
    for (var i = 0; i <= people; i++) {
      if((tmp[i+1] - tmp[i]) >= 0) {
        result = tmp[i+1] - tmp[i]
        dai = dai + Math.abs(result)
      }
    }
    console.log(dai);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main
import (
  "bufio"
  "os"
  "strconv"
  "strings"
  "fmt"
)

func Solve() {
  var N int
  var A []int
  NextInt(&N)
  NextIntSlice(&A)
  ans := 0
  prev := A[0]
  for _, a := range A[1:] {
    if a < prev {
      ans += prev - a
    } else {
      prev = a
    }
  }
  Write(ans)
}

func main() {
  Solve()
  Output()
}

var reader = bufio.NewReaderSize(os.Stdin, 1000000)
var writer = bufio.NewWriter(os.Stdout)
func NextLine() string {
  buffer := make([]byte, 0)
  for true {
    line, isPrefix, err := reader.ReadLine()
    if err != nil { panic(err) }
    buffer = append(buffer, line...)
    if !isPrefix { break }
  }
  return string(buffer)
}
func NextInt(A ...*int) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.Atoi(L[i])
  }
}
func NextIntSlice(A *[]int) {
  L := strings.Split(NextLine(), " ")
  if len(L) == 1 && L[0] == "" {
    (*A) = make([]int, 0)
    return
  }
  (*A) = make([]int, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.Atoi(l)
  }
}
func NextFloat(A ...*float64) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.ParseFloat(L[i], 64)
  }
}
func NextFloatSlice(A *[]float64) {
  L := strings.Split(NextLine(), " ")
  if len(L) == 1 && L[0] == "" {
    (*A) = make([]float64, 0)
    return
  }
  (*A) = make([]float64, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.ParseFloat(l, 64)
  }
}
func Write(S ...interface{}) {
  fmt.Fprintln(writer, S...)
}
func WriteIntSlice(A []int) {
  B := make([]interface{}, len(A))
  for i, a := range A { B[i] = a }
  fmt.Fprintln(writer, B...)
}
func Output() {
  _ = writer.Flush()
}
func MaxInt(A ...int) int {
  max := A[0]
  for _, a := range A {
    if max < a { max = a }
  }
  return max
}
func MinInt(A ...int) int {
  min := A[0]
  for _, a := range A {
    if a < min { min = a }
  }
  return min
}
func SumInt(A ...int) int {
  sum := 0
  for _, a := range A {
    sum += a
  }
  return sum
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
//	"time"
)
var ( 
	N int
	A []int
)



var rdr = bufio.NewReaderSize(os.Stdin, 1000000)

func readLine() string {
    buf := make([]byte, 0, 1000000)
    for {
        l, p, e := rdr.ReadLine()
        if e != nil {
            panic(e)
        }
        buf = append(buf, l...)
        if !p {
            break
        }
    }
    return string(buf)
}  

func stringToArr(str string )[]string{
   return strings.Split( str," ")	
}

func atoi(str string)int{
	 ret,_ := strconv.Atoi(str)
	 return ret
}
func atoi2(str []string)[]int{

	ret:= make([]int,len(str))

	for i,v := range(str){
		ret[i] = atoi(v)
	}
	return ret
}


func calc (a []int)int64{
	current:= a[0]
	var cnt int64
	cnt = int64(0)
	for i:=1; i< len(a); i++{
		if current > a[i]{
			cnt= cnt + int64(current - a[i])
		}else{
			current = a[i]
		}
	
	}
	return cnt

}


func main (){
//	start := time.Now()
N= atoi( readLine())
A= atoi2 ( stringToArr(readLine()))

re:= calc(A)



//s:= atoi2 (stringToArr( readLine()))
 
//N:=s[0]
//X:=s[1]
//T:=s[2]
/*
cnt:=0
for i:=0; i< len(N); i++ {
	n :=  N[i] - '0'
	cnt += int( n)
}
r:="No"

if  cnt % 9 == 0{
	r="Yes"
}*/



fmt.Println(re)
    
   //n,_ := strconv.Atoi( readLine());
   //l:= strings.Split( readLine(), " ");

   /*
   for i:=0; i<n ;i++ {

   }
	
   for i:=1; i<n ;i++ {
	 
   }
 
   for i:=0; i<n ;i++ {
fmt.Println ( person[i].childrenNumber)
   }*/

 //  end := time.Now()
 //  fmt.Printf("%fç§’\n", (end.Sub(start)).Seconds())

}
//  [go]
package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)

	t := make([]int, n)
	for i := 0; i < n; i++ {
			fmt.Scan(&t[i])
	}

	var cnt int = 0

	for i := 0; i < (n - 1); i++ {
		if t[i] > t[i + 1]{
			cnt  += t[i] - t[i + 1]
		}
	}

	fmt.Println(cnt)
}
//  [go]
package main

import (
	// "bufio"
	"fmt"
	// "os"
	// "strconv"
	"math"
)

type height struct {
	human int
	step  int
}

func (h height) Sum() int {
	return h.human + h.step
}

func main() {
	// var N int
	// fmt.Scan(&N)

	// A := make([]height, N)

	// for i := 0; i < N; i++ {
	// 	fmt.Scan(&A[i].human)
	// }

	// // scanner := bufio.NewScanner(os.Stdin)
	// // for i := 0; i < N && scanner.Scan(); i++ {
	// // 	A[i].human, _ = strconv.Atoi(scanner.Text())
	// // }
	// sum, tmp := 0, 0
	// for i := 0; i < N-1; i++ {
	// 	if A[i+1].human >= A[i].Sum() {
	// 		continue
	// 	}
	// 	tmp = A[i].Sum() - A[i+1].human
	// 	A[i+1].step = tmp
	// 	sum += tmp
	// }

	// fmt.Println(sum)

	var N int
	fmt.Scan(&N)
	human := make([]int, N)
	step := make([]int, N)

	for i := 0; i < N; i++ {
		fmt.Scan(&human[i])
	}
	sum := 0
	var Max int
	for i := 0; i < N; i++ {
		Max = int(math.Max(float64(human[i]), float64(Max)))
		sum += Max - human[i]
	}
	fmt.Println(sum)

}
//  [ruby]
N = gets.to_i
A = gets.chomp.split(" ").map(&:to_i)

ans, wk = 0, 0
A.each{|a|
  wk = a if wk < a
  ans += (wk-a)
}

puts ans
//  [ruby]
gets;x=0;p gets.split.sum{x=[a=_1.to_i,x].max;x-a}
//  [ruby]
gets
m=s=t = 0
gets.split.each {
  s += a = _1.to_i
  t += (m<a ? m=a : m)
}
p t-s
//  [ruby]
#people_num = gets.chomp.to_i
# 5
#array = gets.chomp.split(" ").map(&:to_i)
# array = [2, 1, 5, 4, 3]

line = readline.map(&:chomp)
people_num = line[0].to_i
array = line[1].split(" ").map(&:to_i)

# 最終的に追加しなればならない踏み台の合計の高さ
add_height = 0

(1..people_num - 1).each do |n|
    # 自分よりも前の身長だけを格納したローカル配列
    pre_with_me = []
    (0..n - 1).each {|num|
        pre_with_me << array[num]
    }

    # pre_with_meの状態
    # [2]
    # [2, 1]
    # [2, 1, 5]
    # [2, 1, 5, 4]

    # 自分より前にいるやつで一番身長でかいやつを格納する変数
    pre_max = pre_with_me.max 
    if array[n] < pre_max
        gap = pre_max - array[n]
        add_height += gap
    end
end


p add_height
//  [ruby]
people_num = gets.chomp.to_i
# 5
array = gets.chomp.split(" ").map(&:to_i)
# array = [2, 1, 5, 4, 3]

# 最終的に追加しなればならない踏み台の合計の高さ
add_height = 0

(1..people_num - 1).each do |n|
    # 自分よりも前の身長だけを格納したローカル配列
    pre_with_me = []
    (0..n - 1).each {|num|
        pre_with_me << array[num]
    }

    # pre_with_meの状態
    # [2]
    # [2, 1]
    # [2, 1, 5]
    # [2, 1, 5, 4]

    # 自分より前にいるやつで一番身長でかいやつを格納する変数
    pre_max = pre_with_me.max 
    if array[n] < pre_max
        gap = pre_max - array[n]
        add_height += gap
    end
end


p add_height
//  [ruby]
gets
a=gets.split.map &:to_i
m=0
p a.sum{|a| m=[m,a].max m-a}
//  [rust]
use std::cmp;
use std::fmt::Debug;
use std::str::FromStr;
#[allow(dead_code)]
fn read_as_vec<T>() -> Vec<T>
where
    T: FromStr,
    <T as FromStr>::Err: Debug,
{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim()
        .split_whitespace()
        .map(|c| T::from_str(c).unwrap())
        .collect()
}

#[allow(dead_code)]
fn read_as_string() -> String {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

fn main() {
    let line = read_as_vec::<usize>();
    let n: usize = line[0];

    let mut a: Vec<i64> = read_as_vec::<i64>();

    let mut cost: i64 = 0;

    for i in 1..n {
        if a[i - 1] > a[i] {
            cost += (a[i - 1] - a[i]).abs();
            a[i] = a[i - 1];
        }
    }
    println!("{}", cost);
}
//  [rust]
fn c() {
    input! {
        n: usize,
        a: [u32; n]
    }

    let mut ans = 0_u64;
    let mut check = a[0];

    for v in a.iter() {
        if *v > check {
            check = *v;
        }
        else if *v < check {
            ans += (check - *v) as u64;
        }
    }

    println!("{}", ans);
}

use proconio::{input, marker::Chars};

fn main() {
    c();
}
//  [rust]
#![allow(unused_imports)]
#![allow(unused_variables)]
#![allow(dead_code)]
use proconio::input;
use proconio::marker::*;
use std::cmp::{min, max};
use std::collections::{HashSet, HashMap, BinaryHeap};

struct UnionFind{
    n: usize,
    parent: Vec<usize>,
    size: Vec<usize>,
}

impl UnionFind{
    fn new(n: usize ) -> UnionFind{
        let mut parent = vec![0; n];
        for i in 0..n {
            parent[i] = i;
        }
        let size = vec![1; n];
        UnionFind{n, parent, size}
    }

    fn root(&mut self, x: usize) -> usize{
        if x == self.parent[x]{
            self.parent[x]
        }else{
            let res = self.root(self.parent[x]);
            self.parent[x] = res;
            self.parent[x]
        }
    }

    fn unite(&mut self, x: usize, y: usize){
        let a = self.root(x);
        let b = self.root(y);
        if a == b{
            return;
        }
        if self.size[a] <= self.size[b]{
            self.parent[b] = a;
            self.size[a] += self.size[b];
        }else{
            self.parent[a] = b;
            self.size[b] += self.size[a];
        }
    }

    fn is_same(&mut self, x: usize, y: usize) -> bool{
        self.root(x) == self.root(y)
    }

    fn get_size(&mut self, x: usize) -> usize{
        let a = self.root(x);
        self.size[a]
    }
}

fn main() {
    input! {
        n: usize,
        a: [i32; n],
    }
    let mut ans = 0;
    let mut t = a[0];
    for i in 1..n{
        ans += max(t - a[i], 0);
        t = max(t, a[i]);
    }
    println!("{}", ans);
}
//  [rust]
use proconio::{input};

fn main() {
    input! {
        n: usize,
        alist: [u32; n],
    }

    let mut ans: u32 = 0;
    let mut prev: u32 = 0;
    for a in alist {
        if prev > a {
            let step = prev - a;
            ans += step;
            prev = a + step;
        } else {
            prev = a;
        }
    }

    println!("{}", ans);
}
//  [rust]
pub fn main() {
  fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse::<T>().unwrap()
  }
  fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace().map(|e| e.parse().unwrap()).collect()
  }
  let _ = read::<String>();
  let a = read_vec::<i64>();


  let mut ans:i64 = 0;
  let mut high:i64 = 0;
  for i in a {
    if high > i {
      ans += high - i;
    } else {
      high = i;
    }
  }
  println!("{}", ans);
}
//  [swift]
let n = readInt()
let a = readArray().lazy.map { Int($0)! }

var acc = 0
var min = 0

for num in a {
  if min > num {
    acc = acc &+ (min - num)
  } else {
    min = num
  }
}

print(acc)

@inlinable @inline(__always) func readInt() -> Int { Int(readLine()!)! }
@inlinable @inline(__always) func readArray(_ separator: Character = " ") -> [String] { readLine()!.split(separator: separator).map(String.init) }
//  [swift]
let n = Int(readLine()!)!
let a = readLine()!.split(separator: " ").map(String.init).lazy.map { Int($0)! }

var acc = 0
var min = 0

for num in a {
  if min > num {
    acc = acc &+ (min - num)
  } else {
    min = num
  }
}

print(acc)
//  [swift]
let n = Int(readLine()!)!
let a = readLine()!.split(separator: " ").map(String.init).map { Int($0)! }

var acc = 0
var min = 0

for num in a {
  if min > num {
    acc = acc &+ (min - num)
  } else {
    min = num
  }
}

print(acc)
//  [swift]
import Foundation

let input1 = readLine()!
let input2 = readLine()!
let n = Int(input1)!
let a = input2.components(separatedBy: " ").map { Double($0)! }
var current = a[0]
var res = 0.0
for i in (1..<n) {
  if (a[i] > current) {
    res += (a[i] - current)
  }
  current = a[i]
}
print(Int(res))
//  [swift]
import Foundation

let input1 = readLine()!
let input2 = readLine()!
let n = Int(input1)!
let a = input2.components(separatedBy: " ").map { Int($0)! }
var current = a[0]
var res = 0
for i in (1..<n) {
  if (a[i] > current) {
    res += (a[i] - current)
  }
  current = a[i]
}
print(res)
//  [swift]
import Foundation

let rawData = FileHandle.standardInput.availableData
let scanner = Scanner(string: String(data: rawData, encoding: .ascii)!)

let n = scanner.scanInt()!

var acc = 0
var min = scanner.scanInt()!

for _ in 1..<n {
  let num = scanner.scanInt()!

  if min > num {
    acc += min - num
  } else {
    min = num
  }
}

print(acc)
//  [typescript]
import * as fs from 'fs';

function main(input) {
  input = input.split("\n");
  const N = parseInt(input[0], 10);
  const AList = input[1].split(" ").map(i => parseInt(i, 10));
  let count = 0, last = AList[0];
  for (let i = 1; i < N; i++) {
    count += Math.max(0, last - AList[i]);
    last = Math.max(last, AList[i]);
  }

  console.log('%d', count);
  return 0;
}

main(fs.readFileSync("/dev/stdin", "utf8"));
//  [typescript]
import * as fs from "fs";

const input = fs
  .readFileSync("/dev/stdin", "utf8")
  .split("\n")[1]
  .split(" ")
  .map(Number);
let ans = 0;
let max = input[0];
input.forEach((x,i) => {
  // 後ろの値が小さければ追加の処理;
  if(input[i] < max ) {
    ans +=  max - input[i];
  }else {
    // そうじゃない時は値を更新
  	max = input[i]
  }
});
console.log(ans);
//  [typescript]
import * as fs from "fs";

const input = fs
  .readFileSync("/dev/stdin", "utf8")
  .split("\n")[1]
  .split(" ")
  .map(Number);
let ans = 0;
let max = input[0];
input.forEach((x,i) => {
  // 後ろの値が小さければ追加の処理;
  if(input[i] < max ) {
    console.log(input[i] max);
    ans +=  max - input[i];
  }else {
    // そうじゃない時は値を更新
  	max = input[i]
  }
});
console.log(ans);
//  [typescript]
import * as fs from "fs";

const input = fs
  .readFileSync("/dev/stdin", "utf8")
  .split("\n")[1]
  .split(" ")
  .map(Number);
let ans = 0;
let max = input[0];
input.forEach((x,i,arr) => {
  // 後ろの値が小さければ追加の処理
  if(arr[i] > max ) 
    ans += arr[i] - max;
	max = arr[i];
  }
});
console.log(ans);
//  [typescript]
import * as fs from 'fs';

function main(input) {
  input = input.split("\n");
  const N = parseInt(input[0], 10);
  const AList = input[1].split(" ").map(i => parseInt(i, 10));
  let count = 0;
  for (let i = 1; i < N; i++) {
    count += Math.max(0, AList[i - 1] - AList[i]);
  }

  console.log('%d', count);
  return 0;
}

main(fs.readFileSync("/dev/stdin", "utf8"));
//  [python]
def solve(N, H):
    last_h = float('inf')
    _count = -1
    _max = 0
    for h in H:
        if h <= last_h:
            _count += 1
        else:
            if _max < _count:
                _max = _count
            _count = 0
        last_h = h
    if _max < _count:
        _max = _count
    return _max


if __name__ == '__main__':
    N = int(input())
    H = map(int, input().split())
    
    ans = solve(N, H)
    
    print(ans)
//  [python]
#!/usr/bin/env python3


def solve(N, H):
    last_h = float('inf')
    _max = 0
    _count = -1
    for h in H:
        if h <= last_h:
            _count += 1
        else:
            if _max < _count:
                _max = _count
            _count = 0
        last_h = h
    if _max < _count:
        _max = _count
    return _max


if __name__ == '__main__':
    N = int(input())
    H = map(int, input().split())

    ans = solve(N, H)

    print(ans)
//  [python]
def main():
    input()
    H = map(int, input().split())
    ans = 0
    prev = int(1e9+7)
    cnt = -1
    for cur in H:
        if prev >= cur:
            cnt += 1
        else:
            if ans < cnt:
                ans = cnt
            cnt = 0
        prev = cur
    if ans < cnt:
        ans = cnt
    print(ans)
    return


main()
//  [python]
n = int(input())
H = list(map(int, input().split()))
dp = [0]*n
dp[0] = 1
for i in range(1, n-1):
    if H[i] >= H[i+1]:
        dp[i] += dp[i-1]+1
    else:
        dp[i] = 0
print(max(dp[1:]))
//  [python]
N = int(input())
H = list(map(int,input().split()))
ans = 0

for i in range(N-1):
  p = 0
  if H[i] < H[i+1]:
    if ans < p:
      ans = p
    ans = 0
  else:
    ans += 1

print(ans)
//  [python]
N = int(input())
H = list(map(int, input().split()))
ans = 0
cnt = 0
for i in range(N-1):
    if H[i] > H[i+1]:
        cnt += 1
    else:
        ans = max(cnt, ans)
        cnt = 0 #初期化
ans = max(cnt, ans)
print(ans)
//  [java]
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class Main {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int[] a = na(n);
		int prev = Integer.MAX_VALUE;
		int max = 0;
		int cur = 0;
		for(int i = 0; i < n; i++) {
			if(prev >= a[i]) {
				cur++;
			}
			else {
				cur = 1;
			}
			prev = a[i];
			max = Math.max(max, cur);
		}
		out.println(max - 1);
	}

	void run() throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		if (!INPUT.isEmpty())
			tr(System.currentTimeMillis() - s + "ms");
	}

	public static void main(String[] args) throws Exception {
		new Main().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd() {
		return Double.parseDouble(ns());
	}

	private float nf() {
		return Float.parseFloat(ns());
	}

	private char nc() {
		return (char) skip();
	}

	private String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b))) {
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private static void tr(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}
}
//  [java]
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author KharYusuf
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastReader in = new FastReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        CLower solver = new CLower();
        solver.solve(1, in, out);
        out.close();
    }

    static class CLower {
        public void solve(int testNumber, FastReader s, PrintWriter w) {
            int n = s.nextInt();
            int max = 0, cur = 0, prev = -1;
            for (int i = 0; i < n; i++) {
                int x = s.nextInt();
                if (x > prev) {
                    max = Math.max(max, cur);
                    cur = 0;
                    prev = x;
                } else {
                    cur++;
                    prev = x;
                }
            }
            max = Math.max(cur, max);
            w.println(max);
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {

                curChar = 0;

                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }

            return buf[curChar++];
        }

        public int nextInt() {

            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public boolean isSpaceChar(int c) {

            if (filter != null)
                return filter.isSpaceChar(c);

            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}
//  [java]
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            int N = in.nextInt();
            int[] H = new int[N];
            for (int i = 0; i < N; i++) {
                H[i] = in.nextInt();
            }

            int[] cumsum = new int[N];
            for (int j = N - 1 - 1; j >= 0; j--) {
                if (H[j] >= H[j + 1]) {
                    cumsum[j] = 1 + cumsum[j + 1];
                } else {
                    cumsum[j] = 1;
                }
            }

            int max = 0;
            for (int j = 0; j < N; j++) {
                max = Math.max(max, cumsum[j]);
            }

            System.out.println(max);
        }
    }
}
//  [java]
import java.util.*;

public class Main{
    void solve(){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] h = new int[n];
        for(int i = 0; i < n; i++) h[i] = scan.nextInt();
        int c = 0;
        int out = -1;
        for(int i = 0; i < n - 1; i++){
            if(h[i] >= h[i + 1]) c++;
            else{
                if(c == 0) continue;
                c++;
                out = Math.max(c, out);
                c = 0;
            }
        }
        out = Math.max(out, c);
        System.out.println(out);
        scan.close();
    }

    public static void main(String[] args){
        new Main().solve();
    }
}
//  [java]
import java.util.*;

public class Main{
    void solve(){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] h = new int[n];
        for(int i = 0; i < n; i++){
            h[i] = scan.nextInt();
        }
        int out = 0;
        int max = 0;
        for(int i = 0; i < n - 1; i++){
            if(h[i] >= h[i + 1]) out++;
            else{
                max = Math.max(max, out);
                out = 0;
            }
        }
        System.out.println(max);
    }
    
    public static void main(String[] args){
        new Main().solve();
    }
}
//  [cpp]
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

//今日のコンテストはまたゴミクズだったなぁ

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint();

	int kotae = 0;
	int kari = 0;
	int mae = 0;
	rep(i, N) {
		int h = getint();
		if (mae >= h) kari++;
		else kari = 0;

		kotae = max(kotae, kari);
		mae = h;
	}

	printf("%d", kotae);

	Would you please return 0;
}