import java.io.*;
import java.util.*;

public class Main
{
	private InputStream is;
	private PrintWriter out;
	int time = 0, DP[], start[], end[], dist[], black[], MOD = (int) (1e9 + 7),
			arr[], weight[][], x[], y[], parent[];
	int MAX = 100000, N, K;
	long red[],ans = Long.MAX_VALUE;

	ArrayList<Character>[] amp;
	ArrayList<Pair>[] pmp;
	boolean b[], boo[][];
	Pair prr[];
	HashMap<Pair, Integer> hm = new HashMap();
	long Dp[][][][] = new long[110][110][12][12];

	void soln()
	{
		is = System.in;
		out = new PrintWriter(System.out);
		long s = System.currentTimeMillis();
		solve();

		// out.close();
		out.flush();
		// tr(System.currentTimeMillis() - s + "ms");
	}

	public static void main(String[] args) throws Exception
	{
		new Thread(null, new Runnable()
		{
			public void run()
			{
				try
				{
					// new CODEFORCES().soln();
				} catch (Exception e)
				{
					System.out.println(e);
				}
			}
		}, "1", 1 << 26).start();
		new Main().soln();
	}

	int  cost = 0, D[][];
	char ch[], ch1[];
	int hash = 29;
	TreeSet<Cell> ts;
	int x2, y2;
	HashSet<Integer>[] hs = (HashSet<Integer>[]) new HashSet[110];
	void solve()
	{
		int n = ni();
		arr = na(n);
		if(n==2){
			if(arr[0]==arr[1]){
				System.out.println(1);
			}
			else System.out.println(0);
			return;
		}

		ternary_search(0, n-1);
		/*int p = n-1;
		for(int i = n-1;i>0;i--){
			if(arr[i]>=arr[i-1]){
				p = i;
				break;
			}
		}
		int x = arr[0];
		long fa = 0;
		for(int i = 1; i< p; i++){
			fa+= max(0,x+1-arr[i]);
			x = max(x+1,arr[i]);
		}*/
		System.out.println(ans);
	}
	void ternary_search(int l,int r)
	{
		//System.out.println(l+" "+r+" "+ans);
	//	for(int i : arr) System.out.print(i+" ");
	//	System.out.println();
	    if(r>=l)
	    {
	        int mid1 = l + (r-l)/3;
	        int mid2 = r -  (r-l)/3;
	        long cnt1 = 0, cnt2 = 0;
	        cnt1 = compute(mid1);
	        cnt2 = compute(mid2);
	       // System.out.println(mid1+" "+ cnt1+" "+mid2+" "+cnt2);
	        ans = Math.min(cnt1,cnt2);
	        if(cnt1<cnt2){
	        	ternary_search(l, mid2-1);
	        }
	        else{
	        	ternary_search(mid1+1, r);
	        }
	    }
	    return;
	}
	long compute(int x){
		long ans = 0;
		int c = arr[0];
		for(int i = 1; i<=x;i++){
			ans += max(c+1-arr[i],0);
			c = max(c+1,arr[i]);
		}
		int temp = arr[x];
		arr[x] = max(c+1,arr[x]);
		//SSystem.out.println(arr[x]+" "+ans);
		c = arr[arr.length-1];
		for(int i = arr.length-1;i>x;i--){
			ans += max(c+1-arr[i-1],0);
			c = max(c+1,arr[i-1]);
		}
		arr[x] = temp;
		return ans;
	}
	public int getParent(int x) {
		while (parent[x] != x) {
			parent[x] = parent[parent[x]];
			x = parent[x];
		}
		return x;
	}
	void getFactors(int n,int x){
		for(int i = 1;i*i<=n;i++){
			if(n%i==0){
				hs[x].add(i);
				hs[x].add(n/i);
			}
		}
	}
	void recur(int a, int b, int k){
		if(k==0){
			if(a==x2 && b==y2) ans++;
			return;
		}
		recur(a,b+1,k-1);
		recur(a,b-1,k-1);
		recur(a+1,b,k-1);
		recur(a-1,b,k-1);
	}
	int min(int a, int b)
	{
		return (a<b)?a:b;
	}
	private class Cell implements Comparable<Cell>
	{
		int u, v, s;
		public Cell(int u, int v, int s)
		{
			this.u = u;
			this.v = v;
			this.s = s;
		}
		public int hashCode()
		{
			return Objects.hash();
		}
		public int compareTo(Cell other)
		{
			return (Long.compare(s, other.s) != 0 ? (Long.compare(s, other.s)):(Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u)))
					&((Long.compare(s, other.s) != 0 ? (Long.compare(s, other.s)):(Long.compare(u, other.v)!=0?Long.compare(u, other.v):Long.compare(v, other.u))));
		}
		public String toString()
		{
			return this.u + " " + this.v;
		}
	}

	class Pair implements Comparable<Pair>
	{
		int u, v, i;

		Pair(int u, int v)
		{
			this.u = u;
			this.v = v;
		}

		Pair(int u, int v, int i)
		{
			this.u = u;
			this.v = v;
			this.i = i;
		}

		public int hashCode()
		{
			return Objects.hash();
		}

		public boolean equals(Object o)
		{
			Pair other = (Pair) o;
			return ((u == other.u && v == other.v));
		}

		public int compareTo(Pair other)
		{
			// return Integer.compare(val, other.val);
			return Long.compare(u, other.u) != 0 ? (Long.compare(u, other.u)): (Long.compare(v, other.v));//((Long.compare(u, other.u) != 0 ? (Long.compare(u, other.u)): (Long.compare(v, other.v)))
					//&(Long.compare(u, other.v) != 0 ? (Long.compare(u, other.v)): (Long.compare(v, other.u))));
		}

		public String toString()
		{
			return this.u + " " + this.v;
		}
	}

	int max(int a, int b)
	{
		if (a > b)
			return a;
		return b;
	}

	/*public static class FenwickTree
	{

		int[] array; // 1-indexed array, In this array We save cumulative
						// information to perform efficient range queries and
						// updates

		public FenwickTree(int size)
		{
			array = new int[size + 1];
		}

		public int rsq(int ind)
		{
			assert ind > 0;
			int sum = 0;
			while (ind > 0)
			{
				sum += array[ind];
				// Extracting the portion up to the first significant one of the
				// binary representation of 'ind' and decrementing ind by that
				// number
				ind -= ind & (-ind);
			}
			return sum;
		}

		public int rsq(int a, int b)
		{
			assert b >= a && a > 0 && b > 0;
			return rsq(b) - rsq(a - 1);
		}

		public void update(int ind, int value)
		{
			assert ind > 0;
			while (ind < array.length)
			{
				array[ind] += value;
				// Extracting the portion up to the first significant one of the
				// binary representation of 'ind' and incrementing ind by that
				// number
				ind += ind & (-ind);
			}
		}

		public int size()
		{
			return array.length - 1;
		}
	}
*/
	void buildGraph(int n)
	{
		for (int i = 0; i < n; i++)
		{
			int x1 = ni(), y1 = ni(), z = ni();
			pmp[x1].add(new Pair(y1,z));
		}
	}

	long modInverse(long a, long mOD2)
	{
		return power(a, mOD2 - 2, mOD2);
	}

	long power(long x, long y, long m)
	{
		if (y == 0)
			return 1;
		long p = power(x, y / 2, m) % m;
		p = (p * p) % m;

		return (y % 2 == 0) ? p : (x * p) % m;
	}

	public long gcd(long a, long b)
	{
		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class ST1
	{
		int arr[], st[], size;

		ST1(int a[])
		{
			arr = a.clone();
			size = 10 * arr.length;
			st = new int[size];
			build(0, arr.length - 1, 1);
		}

		void build(int ss, int se, int si)
		{
			if (ss == se)
			{
				st[si] = arr[ss];
				return;
			}
			int mid = (ss + se) / 2;
			int val = 2 * si;
			build(ss, mid, val);
			build(mid + 1, se, val + 1);
			st[si] = Math.min(st[val], st[val + 1]);
		}

		int get(int ss, int se, int l, int r, int si)
		{
			if (l > se || r < ss || l > r)
				return Integer.MAX_VALUE;
			if (l <= ss && r >= se)
				return st[si];
			int mid = (ss + se) / 2;
			int val = 2 * si;
			return Math.min(get(ss, mid, l, r, val),
					get(mid + 1, se, l, r, val + 1));
		}
	}

	static class ST
	{
		int arr[], lazy[], n;

		ST(int a)
		{
			n = a;
			arr = new int[10 * n];
			lazy = new int[10 * n];
		}

		void up(int l, int r, int val)
		{
			update(0, n - 1, 0, l, r, val);
		}

		void update(int l, int r, int c, int x, int y, int val)
		{
			if (lazy[c] != 0) {
				lazy[2 * c + 1] += lazy[c];
				lazy[2 * c + 2] += lazy[c];
				if (l == r)
					arr[c] += lazy[c];
				lazy[c] = 0;
			}
			if (l > r || x > y || l > y || x > r)
				return;
			if (x <= l && y >= r)

			{
				lazy[c] += val;
				return;
			}
			int mid = l + r >> 1;
			update(l, mid, 2 * c + 1, x, y, val);
			update(mid + 1, r, 2 * c + 2, x, y, val);
			arr[c] = Math.max(arr[2 * c + 1], arr[2 * c + 2]);
		}

		int an(int ind)
		{
			return ans(0, n - 1, 0, ind);
		}

		int ans(int l, int r, int c, int ind)
		{
			if (lazy[c] != 0)
			{
				lazy[2 * c + 1] += lazy[c];
				lazy[2 * c + 2] += lazy[c];
				if (l == r)
					arr[c] += lazy[c];
				lazy[c] = 0;
			}
			if (l == r)
				return arr[c];
			int mid = l + r >> 1;
			if (mid >= ind)
				return ans(l, mid, 2 * c + 1, ind);
			return ans(mid + 1, r, 2 * c + 2, ind);
		}
	}

	public static int[] shuffle(int[] a, Random gen)
	{
		for (int i = 0, n = a.length; i < n; i++)
		{
			int ind = gen.nextInt(n - i) + i;
			int d = a[i];
			a[i] = a[ind];
			a[ind] = d;
		}
		return a;
	}

	long power(long x, long y, int mod)
	{
		long ans = 1;
		while (y > 0)
		{
			if (y % 2 == 0)
			{
				x = (x * x) % mod;
				y /= 2;
			} else
			{
				ans = (x * ans) % mod;
				y--;
			}
		}
		return ans;
	}

	// To Get Input
	// Some Buffer Methods
	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 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 boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private void tr(Object... o)
	{
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}
}


/**
 * Created by Aminul on 18-Sep-17.
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class CF847H {
    public static int index;
    public static void main(String[] args)throws Exception {
        FastReader in = new FastReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        int n = in.nextInt();
        long lsum[] = new long[n+5];
        long rsum[] = new long[n+5];
        long a[] = new long[n+5];

        for(int i = 1; i <= n; i++){
            a[i] = in.nextInt();
        }

        long ltemp[] = new long[n+5];

        for(int i = 1; i <= n; i++){
            ltemp[i] = a[i];
            if(ltemp[i] <= ltemp[i-1]){
                lsum[i] = ltemp[i-1] - ltemp[i] + 1L;
                ltemp[i] = ltemp[i-1] + 1L;
            }
            lsum[i] += lsum[i-1];
        }

        long []rtemp = new long[n+5];
        for(int i = n; i >= 1; i--){
            rtemp[i] = a[i];
            if(rtemp[i] <= rtemp[i+1]){
                rsum[i] = rtemp[i+1] - rtemp[i] + 1L;
                rtemp[i] = rtemp[i+1] + 1L;
            }
            rsum[i] += rsum[i+1];
        }

        long min = Long.MAX_VALUE;

        for(int i = 1; i <= n; i++){
            long l = lsum[i];
            long r = rsum[i+1];
            long x = 0;
            if(ltemp[i] == rtemp[i+1]) x = 1;
            min = Math.min(min, l+r+x);
           // debug(i, l, r);
        }

        pw.println(min);

        pw.close();
    }

    static void debug(Object...obj) {
        System.err.println(Arrays.deepToString(obj));
    }

    static class FastReader {
        InputStream is;
        private byte[] inbuf = new byte[1024];
        private int lenbuf = 0, ptrbuf = 0;
        static final int ints[] = new int[128];

        public FastReader(InputStream is){
            for(int i='0';i<='9';i++) ints[i]=i-'0';
            this.is = is;
        }

        public 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++];
        }

        public boolean isSpaceChar(int c) {
            return !(c >= 33 && c <= 126);
        }
        public int skip() {
            int b;
            while((b = readByte()) != -1 && isSpaceChar(b));
            return b;
        }

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

        public int nextInt(){
            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<<3) + (num<<1) + ints[b];
                }else{
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

        public long nextLong() {
            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<<3) + (num<<1) + ints[b];
                }else{
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }
       /* public char nextChar() {
            return (char)skip();
        }*/

        public char[] next(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);
        }
    }
}


/**
 * Created by Aminul on 18-Sep-17.
 */

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class CF847H {
    public static int index;
    public static void main(String[] args)throws Exception {
        FastReader in = new FastReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        int n = in.nextInt();
        long lsum[] = new long[n+5];
        long rsum[] = new long[n+5];
        long a[] = new long[n+5];
        for(int i = 1; i <= n; i++){
            a[i] = in.nextInt();
        }

        long temp[] = new long[n+5];
        //temp[1] = a[1];

        for(int i = 1; i <= n; i++){
            temp[i] = a[i];
            if(temp[i] <= temp[i-1]){
                lsum[i] = temp[i-1] - temp[i] + 1;
                temp[i] = temp[i-1] + 1;
            }
            lsum[i] += lsum[i-1];
          //  debug(i, lsum[i], temp[i]);
        }

        temp = new long[n+5];
        for(int i = n; i >= 1; i--){
            temp[i] = a[i];
            if(temp[i] <= temp[i+1]){
                rsum[i] = temp[i+1] - temp[i] + 1;
                temp[i] = temp[i+1] + 1;
            }

            rsum[i] += rsum[i+1];
           // debug(i, rsum[i], temp[i]);
        }

        long min = Long.MAX_VALUE;

        for(int i = 1; i <= n; i++){
            long l = lsum[i];
            long r = rsum[i+1];
            min = Math.min(min, l+r);
           // debug(i, l, r);
        }

        pw.println(min);

        pw.close();
    }

    static void debug(Object...obj) {
        System.err.println(Arrays.deepToString(obj));
    }

    static class FastReader {
        InputStream is;
        private byte[] inbuf = new byte[1024];
        private int lenbuf = 0, ptrbuf = 0;
        static final int ints[] = new int[128];

        public FastReader(InputStream is){
            for(int i='0';i<='9';i++) ints[i]=i-'0';
            this.is = is;
        }

        public 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++];
        }

        public boolean isSpaceChar(int c) {
            return !(c >= 33 && c <= 126);
        }
        public int skip() {
            int b;
            while((b = readByte()) != -1 && isSpaceChar(b));
            return b;
        }

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

        public int nextInt(){
            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<<3) + (num<<1) + ints[b];
                }else{
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

        public long nextLong() {
            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<<3) + (num<<1) + ints[b];
                }else{
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }
       /* public char nextChar() {
            return (char)skip();
        }*/

        public char[] next(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);
        }
    }
}


import java.awt.*;
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;

public class BST {

    static class Parser
    {
        final private int BUFFER_SIZE = 1 << 16;

        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Parser(InputStream in)
        {
            din = new DataInputStream(in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public long nextLong() throws Exception
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = c == '-';
            if (neg) c = read();
            do
            {
                ret = ret * 10 + c - '0';
                c = read();
            } while (c > ' ');
            if (neg) return -ret;
            return ret;
        }

        //reads in the next string
        public String next() throws Exception
        {
            StringBuilder ret =  new StringBuilder();
            byte c = read();
            while (c <= ' ') c = read();
            do
            {
                ret = ret.append((char)c);
                c = read();
            } while (c > ' ');
            return ret.toString();
        }

        public int nextInt() throws Exception
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = c == '-';
            if (neg) c = read();
            do
            {
                ret = ret * 10 + c - '0';
                c = read();
            } while (c > ' ');
            if (neg) return -ret;
            return ret;
        }

        private void fillBuffer() throws Exception
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1) buffer[0] = -1;
        }

        private byte read() throws Exception
        {
            if (bufferPointer == bytesRead) fillBuffer();
            return buffer[bufferPointer++];
        }
    }
    static class OutputWriter
    {
        private PrintWriter writer;

        public OutputWriter(OutputStream stream)
        {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                    stream)));
        }

        public OutputWriter(Writer writer)
        {
            this.writer = new PrintWriter(writer);
        }

        public void println(int x)
        {
            writer.println(x);
        }

        public void print(int x)
        {
            writer.print(x);
        }

        public void println(char x)
        {
            writer.println(x);
        }

        public void print(char x)
        {
            writer.print(x);
        }

        public void println(int array[], int size)
        {
            for (int i = 0; i < size; i++)
                println(array[i]);
        }

        public void print(int array[], int size)
        {
            for (int i = 0; i < size; i++)
                print(array[i] + " ");
        }

        public void println(long x)
        {
            writer.println(x);
        }

        public void print(long x)
        {
            writer.print(x);
        }

        public void println(long array[], int size)
        {
            for (int i = 0; i < size; i++)
                println(array[i]);
        }

        public void print(long array[], int size)
        {
            for (int i = 0; i < size; i++)
                print(array[i]);
        }

        public void println(float num)
        {
            writer.println(num);
        }

        public void print(float num)
        {
            writer.print(num);
        }

        public void println(double num)
        {
            writer.println(num);
        }

        public void print(double num)
        {
            writer.print(num);
        }

        public void println(String s)
        {
            writer.println(s);
        }

        public void print(String s)
        {
            writer.print(s);
        }

        public void println()
        {
            writer.println();
        }

        public void printSpace()
        {
            writer.print(" ");
        }

        public void printf(String format, Object args)
        {
            writer.printf(format, args);
        }

        public void flush()
        {
            writer.flush();
        }

        public void close()
        {
            writer.close();
        }

    }

    public static void main(String args[]) throws Exception {
        Parser s = new Parser(System.in);
        OutputWriter out = new OutputWriter(System.out);
        int N=s.nextInt();
        long arr[]=new long[N];
        long tot=0;
        for (int i = 0; i <N ; i++) {
            arr[i]=s.nextLong();
            tot+=arr[i];
        }
        long left[]=new long[N];
        long right[]=new long[N];
        left[0]=arr[0];
        right[N-1]=arr[N-1];
        for (int i = 1; i <N ; i++) {
            if(arr[i]>left[i-1]){
                left[i]=arr[i];
            }
            else
                left[i]=left[i-1]+1;
        }
        for (int i = N-2; i >=0 ; i--) {
            if(arr[i]>right[i+1]){
                right[i]=arr[i];
            }
            else
                right[i]=right[i+1]+1;
        }
        long leftsum[]=new long[N];
        long rightsum[]=new long[N];
        leftsum[0]=left[0];
        rightsum[N-1]=right[N-1];
        for (int i = 1; i <N ; i++) {
            leftsum[i]=leftsum[i-1]+left[i];
        }
        for (int i = N-2; i >=0 ; i--) {
            rightsum[i]=rightsum[i+1]+right[i];
        }

        long min=Long.MAX_VALUE;
        for (int i = 0; i <N-1 ; i++) {
            long sum=leftsum[i]+rightsum[i+1];
            sum=sum+(right[i+1]-left[i]+1);
            long y=sum-tot;
            if(min>y)
                min=y;
        }
        long x=leftsum[N-1]-tot;
        if(min>x)
            min=x;
        if(min<0)
            min=0;
        System.out.println(min);

    }
}


import java.awt.*;
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;

public class BST {

    static class Parser
    {
        final private int BUFFER_SIZE = 1 << 16;

        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Parser(InputStream in)
        {
            din = new DataInputStream(in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public long nextLong() throws Exception
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = c == '-';
            if (neg) c = read();
            do
            {
                ret = ret * 10 + c - '0';
                c = read();
            } while (c > ' ');
            if (neg) return -ret;
            return ret;
        }

        //reads in the next string
        public String next() throws Exception
        {
            StringBuilder ret =  new StringBuilder();
            byte c = read();
            while (c <= ' ') c = read();
            do
            {
                ret = ret.append((char)c);
                c = read();
            } while (c > ' ');
            return ret.toString();
        }

        public int nextInt() throws Exception
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ') c = read();
            boolean neg = c == '-';
            if (neg) c = read();
            do
            {
                ret = ret * 10 + c - '0';
                c = read();
            } while (c > ' ');
            if (neg) return -ret;
            return ret;
        }

        private void fillBuffer() throws Exception
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1) buffer[0] = -1;
        }

        private byte read() throws Exception
        {
            if (bufferPointer == bytesRead) fillBuffer();
            return buffer[bufferPointer++];
        }
    }
    static class OutputWriter
    {
        private PrintWriter writer;

        public OutputWriter(OutputStream stream)
        {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                    stream)));
        }

        public OutputWriter(Writer writer)
        {
            this.writer = new PrintWriter(writer);
        }

        public void println(int x)
        {
            writer.println(x);
        }

        public void print(int x)
        {
            writer.print(x);
        }

        public void println(char x)
        {
            writer.println(x);
        }

        public void print(char x)
        {
            writer.print(x);
        }

        public void println(int array[], int size)
        {
            for (int i = 0; i < size; i++)
                println(array[i]);
        }

        public void print(int array[], int size)
        {
            for (int i = 0; i < size; i++)
                print(array[i] + " ");
        }

        public void println(long x)
        {
            writer.println(x);
        }

        public void print(long x)
        {
            writer.print(x);
        }

        public void println(long array[], int size)
        {
            for (int i = 0; i < size; i++)
                println(array[i]);
        }

        public void print(long array[], int size)
        {
            for (int i = 0; i < size; i++)
                print(array[i]);
        }

        public void println(float num)
        {
            writer.println(num);
        }

        public void print(float num)
        {
            writer.print(num);
        }

        public void println(double num)
        {
            writer.println(num);
        }

        public void print(double num)
        {
            writer.print(num);
        }

        public void println(String s)
        {
            writer.println(s);
        }

        public void print(String s)
        {
            writer.print(s);
        }

        public void println()
        {
            writer.println();
        }

        public void printSpace()
        {
            writer.print(" ");
        }

        public void printf(String format, Object args)
        {
            writer.printf(format, args);
        }

        public void flush()
        {
            writer.flush();
        }

        public void close()
        {
            writer.close();
        }

    }

    public static void main(String args[]) throws Exception {
        Parser s = new Parser(System.in);
        OutputWriter out = new OutputWriter(System.out);
        int N=s.nextInt();
        long arr[]=new long[N];
        long tot=0;
        for (int i = 0; i <N ; i++) {
            arr[i]=s.nextLong();
            tot+=arr[i];
        }
        long left[]=new long[N];
        long right[]=new long[N];
        left[0]=arr[0];
        right[N-1]=arr[N-1];
        for (int i = 1; i <N ; i++) {
            if(arr[i]>left[i-1]){
                left[i]=arr[i];
            }
            else
                left[i]=left[i-1]+1;
        }
        for (int i = N-2; i >=0 ; i--) {
            if(arr[i]>right[i+1]){
                right[i]=arr[i];
            }
            else
                right[i]=right[i+1]+1;
        }
        long leftsum[]=new long[N];
        long rightsum[]=new long[N];
        leftsum[0]=left[0];
        rightsum[N-1]=right[N-1];
        for (int i = 1; i <N ; i++) {
            leftsum[i]=leftsum[i-1]+left[i];
        }
        for (int i = N-2; i >=0 ; i--) {
            rightsum[i]=rightsum[i+1]+right[i];
        }

        long min=Long.MAX_VALUE;
        for (int i = 0; i <N-1 ; i++) {
            long sum=leftsum[i]+rightsum[i+1];
            if(right[i+1]>=left[i])
            sum=sum+(right[i+1]-left[i]+1);
            long y=sum-tot;
            if(min>y)
                min=y;
        }
        long x=leftsum[N-1]-tot;
        if(min>x)
            min=x;
//        if(min<0)
//            min=0;
        System.out.println(min);

    }
}


import java.io.PrintWriter;
import java.util.Scanner;

public class Task_H {
	public static void main(String[] args) {
		// Scanner scan = new Scanner(new File("input.txt"));
		// PrintWriter out = new PrintWriter("output.txt");
		Scanner scan = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt();
		int []a = new int [n+2];
		for(int i = 1;i<=n;i++){
			a[i] = scan.nextInt();
		}
		long []beg = new long [n+2];
		long []begMax = new long [n+2];
		beg[0] = 0;
		begMax[0] = -1;
		for(int i = 1;i<=n;i++){
			beg[i] = beg[i-1];
			if(a[i] > begMax[i-1]){
				begMax[i] = a[i];
			} else {
				beg[i] += begMax[i-1]+1-a[i];
				begMax[i] = begMax[i-1]+1;
			}
		}
		long []end = new long [n+2];
		long []endMax = new long [n+2];
		end[n+1] = 0;
		endMax[n+1] = -1;
		for(int i = n;i>=1;i--){
			end[i] = end[i+1];
			if(a[i] > endMax[i+1]){
				endMax[i] = a[i];
			} else {
				end[i] += endMax[i+1]+1-a[i];
				endMax[i] = endMax[i+1]+1;
			}
		}
		long min = Integer.MAX_VALUE;
		for(int i = 1;i<=n;i++){
			long minNow = beg[i-1]+end[i+1];
			if(Math.max(begMax[i-1], endMax[i+1])+1 > a[i]){
				minNow += Math.max(begMax[i-1], endMax[i+1])+1-a[i];
			}
			min = Math.min(min, minNow);
		}
		out.println(min);
		out.close();
	}
}


import java.util.*;
import java.io.*;

public class Task_C {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		PrintWriter out = new PrintWriter(new BufferedWriter(
				new OutputStreamWriter(System.out)));

		int n = in.nextInt();
		long k = in.nextLong();

		long l = 1;
		long r = 1000000;

		while (r - l > 1) {
			long m = (r + l) / 2;
			if (m + m * m >= 2 * k) {
				r = m;
			} else {
				l = m;
			}
		}

		if (r+1 > n) {
			out.println("Impossible");
			out.close();
			return;
		}

		long max = (2 + (r - 1)) * r / 2;
		for (int i = 0; i < r; i++) {
			out.print('(');
		}

		if (k - max == 0) {
			out.print('(');
			for (int i = 0; i < r + 1; i++) {
				out.print(')');
			}
		} else {
			for (int i = 0; i < max - k; i++) {
				out.print(')');
			}
			out.print("()");
			for (int i = 0; i < r + (k - max); i++) {
				out.print(')');
			}
		}

		for (int i = 0; i < (n-(r+1)); i++) {
			out.print("()");
		}

		out.close();
	}
}


import java.io.PrintWriter;
import java.util.Scanner;

public class Task_H {
	public static void main(String[] args) {
		// Scanner scan = new Scanner(new File("input.txt"));
		// PrintWriter out = new PrintWriter("output.txt");
		Scanner scan = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt();
		int []a = new int [n+2];
		for(int i = 1;i<=n;i++){
			a[i] = scan.nextInt();
		}
		long []beg = new long [n+2];
		long []begMax = new long [n+2];
		beg[0] = 0;
		begMax[0] = -1;
		for(int i = 1;i<=n;i++){
			beg[i] = beg[i-1];
			if(a[i] > begMax[i-1]){
				begMax[i] = a[i];
			} else {
				beg[i] += begMax[i-1]+1-a[i];
				begMax[i] = begMax[i-1]+1;
			}
		}
		long []end = new long [n+2];
		long []endMax = new long [n+2];
		end[n+1] = 0;
		endMax[n+1] = -1;
		for(int i = n;i>=1;i--){
			end[i] = end[i+1];
			if(a[i] > endMax[i+1]){
				endMax[i] = a[i];
			} else {
				end[i] += endMax[i+1]+1-a[i];
				endMax[i] = endMax[i+1]+1;
			}
		}
		long min = Long.MAX_VALUE;
		for(int i = 1;i<=n;i++){
			long minNow = beg[i-1]+end[i+1];
			if(Math.max(begMax[i-1], endMax[i+1])+1 > a[i]){
				minNow += Math.max(begMax[i-1], endMax[i+1])+1-a[i];
			}
			min = Math.min(min, minNow);
		}
		out.println(min);
		out.close();
	}
}


import java.io.PrintWriter;
import java.util.Scanner;

public class Task_H {
	public static void main(String[] args) {
		// Scanner scan = new Scanner(new File("input.txt"));
		// PrintWriter out = new PrintWriter("output.txt");
		Scanner scan = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		int n = scan.nextInt();
		int []a = new int [n+2];
		for(int i = 1;i<=n;i++){
			a[i] = scan.nextInt();
		}
		int []beg = new int [n+2];
		int []begMax = new int [n+2];
		beg[0] = 0;
		begMax[0] = -1;
		for(int i = 1;i<=n;i++){
			beg[i] = beg[i-1];
			if(a[i] > begMax[i-1]){
				begMax[i] = a[i];
			} else {
				beg[i] += begMax[i-1]+1-a[i];
				begMax[i] = begMax[i-1]+1;
			}
		}
		int []end = new int [n+2];
		int []endMax = new int [n+2];
		end[n+1] = 0;
		endMax[n+1] = -1;
		for(int i = n;i>=1;i--){
			end[i] = end[i+1];
			if(a[i] > endMax[i+1]){
				endMax[i] = a[i];
			} else {
				end[i] += endMax[i+1]+1-a[i];
				endMax[i] = endMax[i+1]+1;
			}
		}
		int min = Integer.MAX_VALUE;
		for(int i = 1;i<=n;i++){
			int minNow = beg[i-1]+end[i+1];
			if(Math.max(begMax[i-1], endMax[i+1])+1 > a[i]){
				minNow += Math.max(begMax[i-1], endMax[i+1])+1-a[i];
			}
			min = Math.min(min, minNow);
		}
		out.println(min);
		out.close();
	}
}


import java.io.*;
import java.util.*;

public class H implements Runnable {

    private void solve() throws IOException {
        int n = readInt();
        int[] left = new int[n], right = new int[n];
        long[] ansL = new long[n + 1],ansR = new long[n + 1];
        for (int i = 0; i < n; i++) {
            right[i] = left[i] = readInt();
        }
        for (int i = n - 2; i >= 0; i--) {
            if (left[i] <= left[i + 1]) {
                ansL[i] = left[i+1] - left[i]  + 1;
                left[i] += left[i+1] - left[i] + 1;
            }
            ansL[i] += ansL[i + 1];
        }
        for (int i = 0; i < n-1; i++) {
            if (right[i+1] <= right[i]) {
                ansR[i + 2] = right[i] - right[i+1] + 1;
                right[i+1] +=right[i] - right[i+1] + 1;
            }
            ansR[i + 2] += ansR[i+1];
        }
        long ans = Math.min(ansL[0] + ansR[0], ansL[n] + ansR[n]);
        for (int i = 1; i < n; i++)
                ans = Math.min(ans, ansL[i] + ansR[i] + (left[i]==right[i-1]?1:0));
        out.println(ans);
    }

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

    class pair implements Comparable<pair> {
        int v, type;
        long x;

        pair(int v, long x, int type) {
            this.x = x;
            this.v = v;
            this.type = type;
        }

        public int compareTo(pair other) {
            return Long.compare(this.x, other.x);
        }
    }

    private void init() throws FileNotFoundException {
        Locale.setDefault(Locale.US);
        String fileName = "";
        if (fileName.isEmpty()) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader(fileName + ".in"));
            out = new PrintWriter(fileName + ".out");
        }
    }

    public void run() {
        try {
            init();
            solve();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    private static BufferedReader in;
    private static StringTokenizer tok;
    private static PrintWriter out;

    private static String readToken() throws IOException {
        while (tok == null || !tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    private static int readInt() throws IOException {
        return Integer.parseInt(readToken());
    }

    private static double readDouble() throws IOException {
        return Double.parseDouble(readToken());
    }

    private static long readLong() throws IOException {
        return Long.parseLong(readToken());
    }
}


import java.io.*;
import java.util.*;
public class H847
{
    public static void main(String args[])throws IOException
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int arr[]=new int[n];
        for(int i=0;i<n;i++)
        {
            arr[i]=sc.nextInt();
        }
        if(n==1)
            System.out.println(0);
        else if(n==2)
        {
            if(arr[0]==arr[1])
                System.out.println(1);
            else
                System.out.println(0);
        }
        else
        {
            long prev=arr[0];
            long asc[]=new long[n];
            long des[]=new long[n];
            long val[]=new long[n];
            val[0]=arr[0];
            int i=1;
            while(i<n)
            {
                if(arr[i]>prev)
                {
                    asc[i]=asc[i-1];
                    prev=arr[i];
                }
                else
                {
                    long diff=prev+1-arr[i];
                    asc[i]=asc[i-1]+diff;
                    prev++;
                }
                val[i]=prev;
                //System.out.println(i+" "+asc[i]+" "+val[i]);
                i++;
            }
            long min=Long.MAX_VALUE;
            min=Math.min(min,asc[n-1]);
            long d=arr[n-1];
            for(int x=n-2;x>=0;x--)
            {
                long temp=asc[x];
                if(val[x]>d)
                {
                    min=Math.min(min,temp+des[x+1]);
                }
                else
                {
                    long diff=d+1-val[x];
                    min=Math.min(min,temp+diff+des[x+1]);
                }
                if(arr[x]>d)
                {
                    d=arr[x];
                    des[x]=des[x+1];
                }
                else
                {
                    d=d+1;
                    des[x]=des[x+1]+d-arr[x];
                }
            }
            min=Math.min(min,des[0]);
            System.out.println(min);
        }
    }
}


import java.io.*;
import java.util.*;

public class E{

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

		int N = sc.nextInt();

		Load[] loads = new Load[N];

		for(int i = 0 ; i < N ; i++) loads[i] = new Load(sc.nextInt());

		if(N == 1){
			System.out.println(0);
			System.exit(0);
		}
		else if(N == 2){
			if(loads[0].val == loads[1].val){
				System.out.println(1);
				System.exit(0);
			}
			System.out.println(0);
			System.exit(0);
		}

		long ctr = 0;

		long min = loads[0].val + 1;
		for(int i = 1 ; i < N - 1 ; i++){
			if(loads[i].val < min){
				loads[i].add = min - loads[i].val;
			}
			min = loads[i].val + loads[i].add + 1;
			ctr += loads[i].add;

		}

		long res = ctr;
//		System.out.println("Start is " + res);

		for(int i = N-2 ; i > 0 ; i--){
//			System.out.print("At idx " + i + " val is " + (loads[i].val + loads[i].add));
			long tmp = Math.max(loads[i+1].val + loads[i+1].add + 1, loads[i].val);
			tmp = Math.min(tmp, loads[i].val + loads[i].add);
			if(tmp < loads[i].val + loads[i].add && tmp < loads[i-1].val + loads[i-1].add){	//  &&
				ctr -= loads[i].add;
				loads[i].add = tmp - loads[i].val;
				ctr += loads[i].add;
			}
			else{
				break;
			}
			res = Math.min(res, ctr);
//			System.out.println(" It is reduced to " + (loads[i].val + loads[i].add));
		}

		System.out.println(res);
	}

}

class Load{
	long val;
	long add;

	Load(int va){
		val = va;
	}
}

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

    public FastScannerE(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 String next()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    public String nextLine()
    {
        int c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isLineEndChar(c));
        return res.toString();
    }

    public double nextDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, nextInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }

    public long nextLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long 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 boolean isLineEndChar(int c)
    {
        if (filter != null)
            return filter.isSpaceChar(c);
        return c == '\n' || c == '\r' || c == -1;
    }

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


import java.io.*;
import java.util.*;

public class E{

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

		int N = sc.nextInt();

		Load[] loads = new Load[N];

		for(int i = 0 ; i < N ; i++) loads[i] = new Load(sc.nextInt());

		if(N == 1){
			System.out.println(0);
			System.exit(0);
		}
		else if(N == 2){
			if(loads[0].val == loads[1].val){
				System.out.println(1);
				System.exit(0);
			}
			System.out.println(0);
			System.exit(0);
		}

		long ctr = 0;

		long min = loads[0].val + 1;
		for(int i = 1 ; i < N - 1 ; i++){
			if(loads[i].val < min){
				loads[i].add = min - loads[i].val;
			}
			min = loads[i].val + loads[i].add + 1;
			ctr += loads[i].add;
		}

		long res = ctr;

		for(int i = N-2 ; i > 0 ; i--){
			long tmp = Math.max(loads[i+1].val + loads[i+1].add + 1, loads[i].val);
			if(tmp < loads[i].val + loads[i].add){
				ctr -= loads[i].add;
				loads[i].add = tmp - loads[i].val;
				ctr += loads[i].add;
			}
			else{
				break;
			}
			res = Math.min(res, ctr);
		}

		System.out.println(res);
	}

}

class Load{
	long val;
	long add;

	Load(int va){
		val = va;
	}
}

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

    public FastScannerE(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 String next()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    public String nextLine()
    {
        int c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isLineEndChar(c));
        return res.toString();
    }

    public double nextDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, nextInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }

    public long nextLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long 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 boolean isLineEndChar(int c)
    {
        if (filter != null)
            return filter.isSpaceChar(c);
        return c == '\n' || c == '\r' || c == -1;
    }

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


import java.io.*;
import java.util.*;

public class E{

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

		int N = sc.nextInt();

		Load[] loads = new Load[N];

		for(int i = 0 ; i < N ; i++) loads[i] = new Load(sc.nextInt());

		if(N == 1){
			System.out.println(0);
			System.exit(0);
		}
		else if(N == 2){
			if(loads[0].val == loads[1].val){
				System.out.println(1);
				System.exit(0);
			}
			System.out.println(0);
			System.exit(0);
		}

		long ctr = 0;

		long min = loads[0].val + 1;
		for(int i = 1 ; i < N - 1 ; i++){
			if(loads[i].val < min){
				loads[i].add = min - loads[i].val;
			}
			min = loads[i].val + loads[i].add + 1;
			ctr += loads[i].add;

		}

		long res = ctr;
//		System.out.println("Start is " + res);

		for(int i = N-2 ; i >= 0 ; i--){
			long tmp = Math.max(loads[i+1].val + loads[i+1].add + 1, loads[i].val);
			if(tmp < loads[i].val + loads[i].add){
				ctr -= loads[i].add;
				loads[i].add = tmp - loads[i].val;
				ctr += loads[i].add;
			}
			res = Math.min(res, ctr);
		}

		System.out.println(res);
	}

}

class Load{
	long val;
	long add;

	Load(int va){
		val = va;
	}
}

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

    public FastScannerE(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 String next()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    public String nextLine()
    {
        int c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isLineEndChar(c));
        return res.toString();
    }

    public double nextDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, nextInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }

    public long nextLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long 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 boolean isLineEndChar(int c)
    {
        if (filter != null)
            return filter.isSpaceChar(c);
        return c == '\n' || c == '\r' || c == -1;
    }

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


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class H implements Runnable {
    private void solve() throws IOException {
        int n = readInt();
        long[] a = new long[n];
        for (int i = 0; i < n; i++) {
            a[i] = readLong();
        }

        long[] prefSum = new long[n];
        long[] prefVal = new long[n];
        prefVal[0] = a[0];
        for (int i = 1; i < n; i++) {
            prefSum[i] += prefSum[i - 1];
            if (prefVal[i - 1] >= a[i]) {
                long newVal = prefVal[i - 1] + 1;
                prefSum[i] += newVal - a[i];
                prefVal[i] = newVal;
            } else {
                prefVal[i] = a[i];
            }
        }

        long[] suffSum = new long[n];
        long[] suffVal = new long[n];
        suffVal[n - 1] = a[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            suffSum[i] += suffSum[i + 1];
            if (a[i] <= suffVal[i + 1]) {
                long newVal = suffVal[i + 1] + 1;
                suffSum[i] += newVal - a[i];
                suffVal[i] = newVal;
            } else {
                suffVal[i] = a[i];
            }
        }

        long bestAns = Long.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            long leftAns = (i == 0) ? 0 : prefSum[i - 1];
            long rightAns = (i == n - 1) ? 0 : suffSum[i + 1];
            long midVal = Math.max(prefVal[i], suffVal[i]);
            long midAns = midVal - a[i];
            long ans = leftAns + rightAns + midAns;
//            System.err.println(i + " " + leftAns + " " + midAns + " " + rightAns);
            bestAns = Math.min(bestAns, ans);
        }

        out.println(bestAns);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public static void main(String[] args) {
        new Thread(null, new H(), "", 128 * (1L << 20)).start();
    }

    private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    private BufferedReader reader;
    private StringTokenizer tokenizer;
    private PrintWriter out;

    @Override
    public void run() {
        try {
            if (ONLINE_JUDGE) {
                reader = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                reader = new BufferedReader(new FileReader("input.txt"));
                out = new PrintWriter("output.txt");
            }
            solve();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                // nothing
            }
            out.close();
        }
    }

    private String readString() throws IOException {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }

    @SuppressWarnings("unused")
    private int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    @SuppressWarnings("unused")
    private long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    @SuppressWarnings("unused")
    private double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }
}


/*
 * Author Ayub Subhaniya
 * Institute DA-IICT
 */

import java.io.*;
import java.math.*;
import java.util.*;

public class Codeforces429C
{

	InputStream in;
	PrintWriter out;

	void solve()
	{
		int n=ni();
		long a[]=new long[n];
		for (int i=0;i<n;i++)
			a[i]=nl();

		long left[]=new long[n];
		long right[]=new long[n];
		long lrequest[]=new long[n];
		long rrequest[]=new long[n];
		left[0]=a[0];
		for (int i=1;i<n;i++)
		{
			left[i]=Math.max(left[i-1]+1, a[i]);
			lrequest[i]=lrequest[i-1]+left[i-1]-a[i-1];
		}
		right[n-1]=a[n-1];
		for (int i=n-2;i>=0;i--)
		{
			right[i]=Math.max(right[i+1]+1, a[i]);
			rrequest[i]=rrequest[i+1]+right[i+1]-a[i+1];
		}

		long min=Long.MAX_VALUE;
		for (int i=0;i<n;i++)
			min=Math.min(lrequest[i]+rrequest[i]+Math.max(left[i], right[i])-a[i], min);
		out.println(min);
	}

	void run() throws Exception
	{
		String INPUT = "C:/Users/ayubs/Desktop/input.txt";
		in = oj ? System.in : new FileInputStream(INPUT);
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis() - s + "ms");

	}
	public static void main(String[] args) throws Exception
	{
		new Codeforces429C().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 = in.read(inbuf);
			}
			catch (IOException e)
			{
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

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

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

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

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

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(inSpaceChar(b)))
		{ // when nextLine, (inSpaceChar(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 && !(inSpaceChar(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 boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private void tr(Object... o)
	{
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}

}


#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define Max 2*100005
int main()
{
    int n;
    while(cin>>n)
    {
        int ara[n+5];
        int ara1[n+5],ara2[n+5],a[n+5];

        for(int i=0;i<n;i++){
            cin>>ara[i];
            ara1[i]=ara[i];
            ara2[i]=ara[i];
        }

        int pre=0;
        for(int i=0;i<n;i++)
        {
            if(ara1[i]<=pre){
                ara1[i] = pre + 1;
            }
            pre = ara1[i];
        }
        pre=0;
        for(int i=n-1;i>=0;i--){
            if(ara2[i]<=pre){
                ara2[i] = pre + 1;
            }
            pre = ara2[i];
        }
        int sum=0;
        for(int i=0;i<n;i++){
            a[i]=min(ara1[i],ara2[i]);
            sum+=abs(a[i] - ara[i]);
        }
       /*
        for(int i=0;i<n;i++){
            cout<<ara1[i]<<' ';
        }
        cout<<endl;
        for(int i=0;i<n;i++) cout<<ara2[i]<<' ';
        cout<<endl;
        for(int i=0;i<n;i++) cout<<a[i]<<' ';
        cout<<endl;*/
        for(int i=1;i<n;i++){
            if(a[i]==a[i-1]) sum++;
        }
        cout<<sum<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ll long long
#define pb push_back
#define Max 2*100005
int main()
{
    int n;
    while(cin>>n)
    {
        ll ara[n+5];
       ll ara1[n+5],ara2[n+5],a[n+5];

        for(int i=0;i<n;i++){
            cin>>ara[i];
            ara1[i]=ara[i];
            ara2[i]=ara[i];
        }

        ll pre=0;
        for(int i=0;i<n;i++)
        {
            if(ara1[i]<=pre){
                ara1[i] = pre + 1;
            }
            pre = ara1[i];
        }
        pre=0;
        for(int i=n-1;i>=0;i--){
            if(ara2[i]<=pre){
                ara2[i] = pre + 1;
            }
            pre = ara2[i];
        }
        ll sum=0;
        for(int i=0;i<n;i++){
            a[i]=min(ara1[i],ara2[i]);
            sum+=abs(a[i] - ara[i]);
        }
       /*
        for(int i=0;i<n;i++){
            cout<<ara1[i]<<' ';
        }
        cout<<endl;
        for(int i=0;i<n;i++) cout<<ara2[i]<<' ';
        cout<<endl;
        for(int i=0;i<n;i++) cout<<a[i]<<' ';
        cout<<endl;*/
        for(int i=1;i<n;i++){
            if(a[i]==a[i-1]) sum++;
        }
        cout<<sum<<endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define Max 2*100005
int main()
{
    int n;
    while(cin>>n)
    {
        int ara[n+5];
        for(int i=1;i<=n;i++) cin>>ara[i];
        int x=-1,y=-1;
        for(int i=1;i<=n;i++){
            if(i+1<=n and ara[i]>=ara[i+1]){
                    x=i;
                    break;
            }
        }
        for(int i=n;i>=1;i--){
            if(i-1>=1 and ara[i]>=ara[i-1]){
                y=i;
                break;
            }
        }
        int ans=0;
        if(x==-1 or y==-1 or (x==y)) cout<<0<<endl;
        else{
            for(int i=x+1;i<y;i++){
                int t=ara[i];
                while(true)
                {
                    if(ara[i-1]>=t){
                        ans++;
                        t++;
                    }
                    else break;

                }
                ara[i]=t;
                    if(i+1<y and ara[i]==ara[i+1]){
                        ara[i]=ara[i]+1;
                        ans++;
                    }
              }
              cout<<ans<<endl;
        }

    }
}


#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <set>
#include <map>
using namespace std;

typedef long long ll;
typedef double lf;
typedef long double Lf;
typedef pair <int,int> pii;
typedef pair <ll, ll> pll;

#define TRACE(x) cerr << #x << "  " << x << endl
#define FOR(i, a, b) for (int i = (a); i < int(b); i++)
#define REP(i, n) FOR(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define _ << " " <<

#define fi first
#define sec second
#define mp make_pair

const int MAXN = 100100;

int n, p[MAXN];
ll sol[MAXN][2], p1[MAXN][2];

int main() {
  scanf("%d",&n);
  REP(i, n) scanf("%d",&p[i]);
  ll last = p[0];
  p1[0][0] = p[0];
  p1[n - 1][1] = p[n - 1];
  FOR(i, 1, n) {
    sol[i][0] = sol[i - 1][0];
    if (p[i] > last) {
      last = p[i];
      p1[i][0] = p[i];
      continue;
    }
    sol[i][0] += last - p[i] + 1;
    last++;
    p1[i][0] = last;
  }

  last = p[n - 1];
  for (int i = n - 2; i >= 0; i--) {
    sol[i][1] = sol[i + 1][1];
    if (p[i] > last) {
      last = p[i];
      p1[i][1] = p[i];
      continue;
    }
    sol[i][1] += last - p[i] + 1;
    last++;
    p1[i][1] = last;
  }

  ll ans = (1LL << 60);
  REP(i, n - 1) {
    ll tmp = sol[i][0] + sol[i + 1][1];
    if (p1[i + 1][1] == p1[i][0]) tmp++;
    ans = min(ans, tmp);
  }
  if (n == 1) ans = 0;
  printf("%lld\n",ans);
  return 0;
}


#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <set>
#include <map>
using namespace std;

typedef long long ll;
typedef double lf;
typedef long double Lf;
typedef pair <int,int> pii;
typedef pair <ll, ll> pll;

#define TRACE(x) cerr << #x << "  " << x << endl
#define FOR(i, a, b) for (int i = (a); i < int(b); i++)
#define REP(i, n) FOR(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define _ << " " <<

#define fi first
#define sec second
#define mp make_pair

const int MAXN = 100100;

int n, p[MAXN];
ll sol[MAXN][2], p1[MAXN][2];

int main() {
  scanf("%d",&n);
  REP(i, n) scanf("%d",&p[i]);
  ll last = p[0];
  p1[0][0] = p[0];
  p1[n - 1][1] = p[n - 1];
  FOR(i, 1, n) {
    sol[i][0] = sol[i - 1][0];
    if (p[i] > last) {
      last = p[i];
      p1[i][0] = p[i];
      continue;
    }
    sol[i][0] += last - p[i] + 1;
    last++;
    p1[i][0] = last;
  }

  last = p[n - 1];
  for (int i = n - 2; i >= 0; i--) {
    sol[i][1] = sol[i + 1][1];
    if (p[i] > last) {
      last = p[i];
      p1[i][1] = p[i];
      continue;
    }
    sol[i][1] += last - p[i] + 1;
    last++;
    p1[i][1] = last;
  }

  ll ans = (1LL << 60);
  REP(i, n - 1) {
    ll tmp = sol[i][0] + sol[i + 1][1];
    if (p1[i + 1][1] == p1[i][0]) tmp++;
    ans = min(ans, tmp);
  }
  printf("%lld\n",ans);
  return 0;
}


#include<bits/stdc++.h>
#define st first
#define nd second
#define pb push_back
#define mp make_pair
#define mod 1000000007
#define endl '\n'
#define endll puts("")
#define mp3(a,b,c) mp(a,mp(b,c))
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define sol (root+root)
#define sag (sol+1)
#define ort ((bas+son)/2)
using namespace std;
const int N = 1e5+4;
ll n,m,i,j,k,l,x,y,z,u,d;
ll h[N],A[N];
ll pre[N],suf[N],hh[N],s,t;
int main()
{
    cin>>n;
    for(i=1;i<=n;i++)
    {
        scanf("%lld",h+i);
        s=max(s,h[i]);
        A[i]=s;
        pre[i]=pre[i-1]+s-h[i];
        s++;
    }
    s=0;m=mod;
    for(i=n;i>0;i--,s++)
    {
        s=max(s,h[i]);
        suf[i]=suf[i+1]+s-h[i];
        if(i!=n and i!=1)
        {
            t=pre[i-1]+suf[i+1]+max(s,A[i])-h[i];
            m=min(m,t);
        }
    }
    cout<<m<<endl;

}


#include<bits/stdc++.h>
#define st first
#define nd second
#define pb push_back
#define mp make_pair
#define mod 1000000007
#define endl '\n'
#define endll puts("")
#define mp3(a,b,c) mp(a,mp(b,c))
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define sol (root+root)
#define sag (sol+1)
#define ort ((bas+son)/2)
using namespace std;
const int N = 1e5+4;
ll n,m,i,j,k,l,x,y,z,u,d;
ll h[N],A[N];
ll pre[N],suf[N],hh[N],s,t;
int main()
{
    cin>>n;
    for(i=1;i<=n;i++)
    {
        scanf("%lld",h+i);
        s=max(s,h[i]);
        A[i]=s;
        pre[i]=pre[i-1]+s-h[i];
        s++;
    }
    s=0;m=pre[n];
    for(i=n;i>0;i--,s++)
    {
        s=max(s,h[i]);
        suf[i]=suf[i+1]+s-h[i];
        if(i!=n and i!=1)
        {
            t=pre[i-1]+suf[i+1]+max(s,A[i])-h[i];
            m=min(m,t);
        }

    }

    cout<<min(m,suf[1])<<endl;

}


#include<bits/stdc++.h>
#define st first
#define nd second
#define pb push_back
#define mp make_pair
#define mod 1000000007
#define endl '\n'
#define endll puts("")
#define mp3(a,b,c) mp(a,mp(b,c))
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define sol (root+root)
#define sag (sol+1)
#define ort ((bas+son)/2)
using namespace std;
const int N = 1e5+4;
ll n,m,i,j,k,l,x,y,z,u,d;
ll h[N],A[N];
ll pre[N],suf[N],hh[N],s,t;
int main()
{
    cin>>n;
    for(i=1;i<=n;i++)
    {
        scanf("%lld",h+i);
        s=max(s,h[i]);
        A[i]=s;
        pre[i]=pre[i-1]+s-h[i];
        s++;
    }
    s=0;m=1e18+4;
    for(i=n;i>0;i--,s++)
    {
        s=max(s,h[i]);
        suf[i]=suf[i+1]+s-h[i];
        if(i!=n and i!=1)
        {
            t=pre[i-1]+suf[i+1]+max(s,A[i])-h[i];
            m=min(m,t);
        }
    }
    cout<<m<<endl;

}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN =1e5+20;
int arr[MAXN];
ll sum[MAXN];
int main()
{
    ll n,a,r,m;cin>>n>>a>>r>>m;
    for (int i = 1; i <= n; ++i) {
        scanf("%d",&arr[i]);
    }
    sort(arr+1,arr+n+1);
    for (int i = 1; i <= n; ++i) {
        sum[i]=sum[i-1]+arr[i];
    }
    ll ans=1e18;
    {
        ll ave0=sum[n]/n;
        ll mod0=sum[n]%n;
        int idx=lower_bound(arr+1,arr+n+1,ave0)-arr;
        ll a3=(sum[n]-sum[idx-1]-ave0*(n-idx+1)-min(mod0,(n-idx+1)))*m+(n-mod0)*a;
        ans=min(ans,a3);

        ll ave1=sum[n]/n;
        ll mod1=sum[n]%n;
        idx=lower_bound(arr+1,arr+n+1,ave1)-arr;
        ll a4=((idx-1)*ave1-sum[idx-1]+max(mod1-(n-idx+1),0ll))*m+mod1*r;
        ans=min(ans,a4);
    }
    for (ll i = 1; i <= n; ++i) {
        ll a0=(arr[i]*i-sum[i])*a;
        ll a1=((sum[n]-sum[i])-arr[i]*(n-i))*r;
        ans=min(ans,a0+a1);

        ll ave0=(arr[i]*i+sum[n]-sum[i])/n;
        ll mod0=(arr[i]*i+sum[n]-sum[i])%n;
        int idx=lower_bound(arr+1,arr+n+1,ave0)-arr;
        ll a3=(sum[n]-sum[idx-1]-ave0*(n-idx+1)-min(mod0,(n-idx+1)))*m+(n-mod0)*a;
        ans=min(ans,a3+a0);

        ll ave1=(sum[i-1]+arr[i]*(n-i+1))/n;
        ll mod1=(sum[i-1]+arr[i]*(n-i+1))%n;
        idx=lower_bound(arr+1,arr+n+1,ave1)-arr;
        ll a4=((idx-1)*ave1-sum[idx-1]+max(mod1-(n-idx+1),0ll))*m+mod1*r;
        ans=min(ans,a4+a1);
    }
    cout << ans << endl;

    return 0;
}
/*

 10 7 8 3
3 10 4 9 2 7 6 10 4 8

10 7122 8827 3205
452685204 144160553 743427456 403576146 888744473 313727757 22025193 886601085 576370788 787974081

 * */


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN =1e5+20;
int arr[MAXN];
ll sum[MAXN];
int main()
{
    ll n,a,r,m;cin>>n>>a>>r>>m;
    for (int i = 1; i <= n; ++i) {
        scanf("%d",&arr[i]);
    }
    sort(arr+1,arr+n+1);
    for (int i = 1; i <= n; ++i) {
        sum[i]=sum[i-1]+arr[i];
    }
    ll ans=1e18;
    {
        ll ave0=sum[n]/n;
        ll mod0=sum[n]%n;
        int idx=upper_bound(arr+1,arr+n+1,ave0)-arr;
        ll a3=(sum[n]-sum[idx-1]-ave0*(n-idx+1)-mod0)*m+(n-mod0)*a;
        ans=min(ans,a3);

        ll ave1=sum[n]/n;
        ll mod1=sum[n]%n;
        idx=upper_bound(arr+1,arr+n+1,ave1)-arr;
        ll a4=((idx-1)*ave1-sum[idx-1])*m+mod1*r;
        ans=min(ans,a4);
    }
    for (ll i = 1; i <= n; ++i) {
        ll a0=(arr[i]*i-sum[i])*a;
        ll a1=((sum[n]-sum[i])-arr[i]*(n-i))*r;
        ans=min(ans,a0+a1);

        ll ave0=(arr[i]*i+sum[n]-sum[i])/n;
        ll mod0=(arr[i]*i+sum[n]-sum[i])%n;
        int idx=upper_bound(arr+1,arr+n+1,ave0)-arr;
        ll a3=(sum[n]-sum[idx-1]-ave0*(n-idx+1)-mod0)*m+(n-mod0)*a;
        ans=min(ans,a3+a0);

        ll ave1=(sum[i]+arr[i]*(n-i))/n;
        ll mod1=(sum[i]+arr[i]*(n-i))%n;
        idx=upper_bound(arr+1,arr+n+1,ave1)-arr;
        ll a4=((idx-1)*ave1-sum[idx-1])*m+mod1*r;
        ans=min(ans,a4+a1);
    }
    cout << ans << endl;

    return 0;
}
/*

 10 7 8 3
3 10 4 9 2 7 6 10 4 8

 * */


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN =1e5+20;
int arr[MAXN];
ll sum[MAXN];
int main()
{
    ll n,a,r,m;cin>>n>>a>>r>>m;
    for (int i = 1; i <= n; ++i) {
        scanf("%d",&arr[i]);
    }
    sort(arr+1,arr+n+1);
    for (int i = 1; i <= n; ++i) {
        sum[i]=sum[i-1]+arr[i];
    }
    ll ans=1e18;
    {
        ll ave0=sum[n]/n;
        ll mod0=sum[n]%n;
        int idx=lower_bound(arr+1,arr+n+1,ave0)-arr;
        ll a3=(sum[n]-sum[idx-1]-ave0*(n-idx+1)-min(mod0,(n-idx+1)))*m+min((n-mod0)*a,mod0*r);
        ans=min(ans,a3);

        ll ave1=sum[n]/n;
        ll mod1=sum[n]%n;
        idx=lower_bound(arr+1,arr+n+1,ave1)-arr;
        ll a4=((idx-1)*ave1-sum[idx-1]+max(mod1-(n-idx+1),0ll))*m+min(mod1*r,(n-mod1)*a);
        ans=min(ans,a4);
    }
    for (ll i = 1; i <= n; ++i) {
        ll a0=(arr[i]*i-sum[i])*a;
        ll a1=((sum[n]-sum[i])-arr[i]*(n-i))*r;
        ans=min(ans,a0+a1);

        ll ave0=(arr[i]*i+sum[n]-sum[i])/n;
        ll mod0=(arr[i]*i+sum[n]-sum[i])%n;
        int idx=lower_bound(arr+1,arr+n+1,ave0)-arr;
        ll a3=(sum[n]-sum[idx-1]-ave0*(n-idx+1)-min(mod0,(n-idx+1)))*m+min((n-mod0)*a,mod0*r);
        ans=min(ans,a3+a0);

        ll ave1=(sum[i-1]+arr[i]*(n-i+1))/n;
        ll mod1=(sum[i-1]+arr[i]*(n-i+1))%n;
        idx=lower_bound(arr+1,arr+n+1,ave1)-arr;
        ll a4=((idx-1)*ave1-sum[idx-1]+max(mod1-(n-idx+1),0ll))*m+min(mod1*r,(n-mod1)*a);
        ans=min(ans,a4+a1);
    }
    cout << ans << endl;

    return 0;
}
/*

 10 7 8 3
3 10 4 9 2 7 6 10 4 8

10 7122 8827 3205
452685204 144160553 743427456 403576146 888744473 313727757 22025193 886601085 576370788 787974081

 * */


#include<bits/stdc++.h>
#include<fstream>
#include <chrono>
#define ll                    long long int
#define loop(i ,a,b)           for(int i=(int)a;i<(int)b;++i)
#define rloop(i,a,b)          for(int i=(int)a;i<=(int)b;++i)
#define loopl(i,a,b)          for(ll i=(ll)a;i<(ll)b;++i)
#define loopr(i,a,b)          for(int i=(int)a;i>=(int)b;--i)
#define count_1(n)            __builtin_popcountll(n)
#define pb                    push_back
#define eb                    emplace_back
#define ab(a)                 (a<0)?(-1*a):a
#define pc                    putchar_unlocked
#define gc                    getchar_unlocked
#define mset(a,b,c)           loop(i,0,b) a[i]=c
#define F                     first
#define S                     second
#define mp                    make_pair
#define clr(x)                x.clear()
#define MOD                   1000000007
#define MAX1                   1e9
#define MIN                   -1e9
#define itoc(c)               ((char)(((int)'0')+c))
#define vi                    vector<int>
#define vvi                   vector<vi>
#define pll                   pair<ll,ll>
#define pii                   pair<int,int>
#define all(p)                p.begin(),p.end()
#define max(x,y)              (x>y)?x:y
#define min(x,y)              (x<y)?x:y
#define mid(s,e)              (s+(e-s)/2)
#define mini                  INT_MIN
#define ifc(i)                (flag[i>>6]&(1<<((i>>1)&31)))
#define isc(i)                (flag[i>>6]|=(1<<((i>>1)&31)))
#define chk(n)                (n==2||(n>2&&(n&1)&&!ifc(n)))
#define sv()                  int t; scanf("%d",&t); while(t--)
using namespace std;
using namespace std::chrono;
#define MAX   1e16;
ll n,a,b,m;

int ch(int ar[], int k)
{
    ll an1 =0, an2 =0;
    for(int i =0;i<n;i++)
    {
       if(ar[i] < k)
        an1 += k - ar[i];
      else if(ar[i] > k)
        an2 += ar[i] - k;
    }
    ll val1 = an1*a + an2*b;
    ll val2 = 0;
    if(an1 >  an2){
      val2 = m*an2;
      val2 += a*(an1 - an2);
    }
    else
    {
      val2 += m*an1;
      val2 += b*(an2 - an1);
    }
    return min(val1, val2);
}
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin>>n>>a>>b>>m;
  int ar[n];
  if(m > a+b)
    m = a+b;
  for(int i =0;i<n;i++)
    cin>>ar[i];
  ll ma = 1e9;
  ll mi = 0;
  ll ans =mi;
  while(ma >= mi)
    {
        int mid = mi + (ma - mi)/2;
        ll val1 = ch(ar, mid-1);
        ll val2 = ch(ar, mid);
        ll val3 = ch(ar, mid+1);
        //cout<<val1<<" "<<val2<<" "<<val3<<"\n";
        if(ma == mi)
        {
           ans = val2;
           break;
        }
        if(val1 >= val2 && val2 <= val3)
        {
           ans = val2;
           break;
        }
        else if(val1 <= val2 && val2 <= val3)
        {
            ma = mid-1;
        }
        else if(val1 >=  val2 && val2 >= val3)
        {
           mi  = mid+1;
        }

    }
    cout<<ans<<"\n";

}


#include<bits/stdc++.h>
#include<fstream>
#include <chrono>
#define ll                    long long int
#define loop(i ,a,b)           for(int i=(int)a;i<(int)b;++i)
#define rloop(i,a,b)          for(int i=(int)a;i<=(int)b;++i)
#define loopl(i,a,b)          for(ll i=(ll)a;i<(ll)b;++i)
#define loopr(i,a,b)          for(int i=(int)a;i>=(int)b;--i)
#define count_1(n)            __builtin_popcountll(n)
#define pb                    push_back
#define eb                    emplace_back
#define ab(a)                 (a<0)?(-1*a):a
#define pc                    putchar_unlocked
#define gc                    getchar_unlocked
#define mset(a,b,c)           loop(i,0,b) a[i]=c
#define F                     first
#define S                     second
#define mp                    make_pair
#define clr(x)                x.clear()
#define MOD                   1000000007
#define MAX1                   1e9
#define MIN                   -1e9
#define itoc(c)               ((char)(((int)'0')+c))
#define vi                    vector<int>
#define vvi                   vector<vi>
#define pll                   pair<ll,ll>
#define pii                   pair<int,int>
#define all(p)                p.begin(),p.end()
#define max(x,y)              (x>y)?x:y
#define min(x,y)              (x<y)?x:y
#define mid(s,e)              (s+(e-s)/2)
#define mini                  INT_MIN
#define ifc(i)                (flag[i>>6]&(1<<((i>>1)&31)))
#define isc(i)                (flag[i>>6]|=(1<<((i>>1)&31)))
#define chk(n)                (n==2||(n>2&&(n&1)&&!ifc(n)))
#define sv()                  int t; scanf("%d",&t); while(t--)
using namespace std;
using namespace std::chrono;
#define MAX   1e16;
ll n,a,b,m;

int ch(int ar[], int k)
{
    ll an1 =0, an2 =0;
    for(int i =0;i<n;i++)
    {
       if(ar[i] < k)
        an1 += k - ar[i];
      else if(ar[i] > k)
        an2 += ar[i] - k;
    }
    ll val1 = an1*a + an2*b;
    ll val2 = 0;
    if(an1 >  an2){
      val2 = m*an2;
      val2 += a*(an1 - an2);
    }
    else
    {
      val2 += m*an1;
      val2 += b*(an2 - an1);
    }
    return min(val1, val2);
}
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin>>n>>a>>b>>m;
  int ar[n];
  if(m > a+b)
    m = a+b;
  for(int i =0;i<n;i++)
    cin>>ar[i];
  ll ma = 1e9;
  ll mi = 0;
  ll ans =mi;
  while(ma >= mi)
    {
        int mid = mi + (ma - mi)/2;
        ll val1 = ch(ar, mid-1);
        ll val2 = ch(ar, mid);
        ll val3 = ch(ar, mid+1);
        //cout<<val1<<" "<<val2<<" "<<val3<<"\n";
        if(ma == mi)
        {
           ans = val2;
           break;
        }
        ans = val2;
         if(val1 <= val2 && val2 < val3)
        {
            ma = mid-1;
        }
        else if(val1 >  val2 && val2 >= val3)
        {
           mi  = mid+1;
        }
        else
          break;

    }
    cout<<ans<<"\n";

}


    #include<bits/stdc++.h>
    #include<fstream>
    #include <chrono>
    #define ll                    long long int
    #define loop(i ,a,b)           for(int i=(int)a;i<(int)b;++i)
    #define rloop(i,a,b)          for(int i=(int)a;i<=(int)b;++i)
    #define loopl(i,a,b)          for(ll i=(ll)a;i<(ll)b;++i)
    #define loopr(i,a,b)          for(int i=(int)a;i>=(int)b;--i)
    #define count_1(n)            __builtin_popcountll(n)
    #define pb                    push_back
    #define eb                    emplace_back
    #define ab(a)                 (a<0)?(-1*a):a
    #define pc                    putchar_unlocked
    #define gc                    getchar_unlocked
    #define mset(a,b,c)           loop(i,0,b) a[i]=c
    #define F                     first
    #define S                     second
    #define mp                    make_pair
    #define clr(x)                x.clear()
    #define MOD                   1000000007
    #define MAX1                   1e9
    #define MIN                   -1e9
    #define itoc(c)               ((char)(((int)'0')+c))
    #define vi                    vector<int>
    #define vvi                   vector<vi>
    #define pll                   pair<ll,ll>
    #define pii                   pair<int,int>
    #define all(p)                p.begin(),p.end()
    #define max(x,y)              (x>y)?x:y
    #define min(x,y)              (x<y)?x:y
    #define mid(s,e)              (s+(e-s)/2)
    #define mini                  INT_MIN
    #define ifc(i)                (flag[i>>6]&(1<<((i>>1)&31)))
    #define isc(i)                (flag[i>>6]|=(1<<((i>>1)&31)))
    #define chk(n)                (n==2||(n>2&&(n&1)&&!ifc(n)))
    #define sv()                  int t; scanf("%d",&t); while(t--)
    using namespace std;
    using namespace std::chrono;
    #define MAX   1e16;
    ll n,a,b,m;

    int ch(int ar[], int k)
    {
        ll an1 =0, an2 =0;
        for(int i =0;i<n;i++)
        {
           if(ar[i] < k)
            an1 += k - ar[i];
          else if(ar[i] > k)
            an2 += ar[i] - k;
        }
        ll val1 = an1*a + an2*b;
        ll val2 = 0;
        if(an1 >  an2){
          val2 = m*an2;
          val2 += a*(an1 - an2);
        }
        else
        {
          val2 += m*an1;
          val2 += b*(an2 - an1);
        }
        return min(val1, val2);
    }
    int main()
    {
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);
      cin>>n>>a>>b>>m;
      int ar[n];
      for(int i =0;i<n;i++)
        cin>>ar[i];
      ll ma = 2e9;
      ll mi = 0;
      ll ans =0;
      while(ma >=  mi)
        {
            int mid = mi + (ma - mi)/2;
            ll val1 = ch(ar, mid-1);
            ll val2 = ch(ar, mid);
            ll val3 = ch(ar, mid+1);
            //cout<<val1<<" "<<val2<<" "<<val3<<"\n";
            //break;

            if(val1 >= val2 && val2 <= val3)
            {
              //cout<<mid<<" ";
               ans = val2;
               break;
            }
            else if(val1 <= val2 && val2 <= val3)
            {
                ma = mid;
            }
            else if(val1 >=  val2 && val2 >= val3)
            {
               mi  = mid;
            }

        }
        cout<<ans<<"\n";

    }


    #include<bits/stdc++.h>
    #include<fstream>
    #include <chrono>
    #define ll                    long long int
    #define loop(i ,a,b)           for(int i=(int)a;i<(int)b;++i)
    #define rloop(i,a,b)          for(int i=(int)a;i<=(int)b;++i)
    #define loopl(i,a,b)          for(ll i=(ll)a;i<(ll)b;++i)
    #define loopr(i,a,b)          for(int i=(int)a;i>=(int)b;--i)
    #define count_1(n)            __builtin_popcountll(n)
    #define pb                    push_back
    #define eb                    emplace_back
    #define ab(a)                 (a<0)?(-1*a):a
    #define pc                    putchar_unlocked
    #define gc                    getchar_unlocked
    #define mset(a,b,c)           loop(i,0,b) a[i]=c
    #define F                     first
    #define S                     second
    #define mp                    make_pair
    #define clr(x)                x.clear()
    #define MOD                   1000000007
    #define MAX1                   1e9
    #define MIN                   -1e9
    #define itoc(c)               ((char)(((int)'0')+c))
    #define vi                    vector<int>
    #define vvi                   vector<vi>
    #define pll                   pair<ll,ll>
    #define pii                   pair<int,int>
    #define all(p)                p.begin(),p.end()
    #define max(x,y)              (x>y)?x:y
    #define min(x,y)              (x<y)?x:y
    #define mid(s,e)              (s+(e-s)/2)
    #define mini                  INT_MIN
    #define ifc(i)                (flag[i>>6]&(1<<((i>>1)&31)))
    #define isc(i)                (flag[i>>6]|=(1<<((i>>1)&31)))
    #define chk(n)                (n==2||(n>2&&(n&1)&&!ifc(n)))
    #define sv()                  int t; scanf("%d",&t); while(t--)
    using namespace std;
    using namespace std::chrono;
    #define MAX   1e16;
    ll n,a,b,m;

    int ch(ll ar[], int k)
    {
        ll an1 =0, an2 =0;
        for(int i =0;i<n;i++)
        {
           if(ar[i] < k)
            an1 += k - ar[i];
          else if(ar[i] > k)
            an2 += ar[i] - k;
        }
        ll val1 = an1*a + an2*b;
        ll val2 = 0;
        if(an1 >  an2){
          val2 = m*an2;
          val2 += a*(an1 - an2);
        }
        else
        {
          val2 += m*an1;
          val2 += b*(an2 - an1);
        }
        return min(val1, val2);
    }
    int main()
    {
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);
      cin>>n>>a>>b>>m;
      ll ar[n];
      if(m > a+b)
        m = a+b;
      for(int i =0;i<n;i++)
        cin>>ar[i];
      ll ma = 1e9;
      ll mi = 0;
      ll ans =mi;
      while(ma >= mi)
        {
            int mid = mi + (ma - mi)/2;
            ll val1 = ch(ar, mid-1);
            ll val2 = ch(ar, mid);
            ll val3 = ch(ar, mid+1);
            //cout<<val1<<" "<<val2<<" "<<val3<<"\n";
            if(ma == mi)
            {
               ans = val2;
               break;
            }
            if(val1 >= val2 && val2 <= val3)
            {
               ans = val2;
               break;
            }
            else if(val1 <= val2 && val2 <= val3)
            {
                ma = mid-1;
            }
            else if(val1 >=  val2 && val2 >= val3)
            {
               mi  = mid+1;
            }

        }
        cout<<ans<<"\n";

    }


#include<bits/stdc++.h>
#include<fstream>
#include <chrono>
#define ll                    long long int
#define loop(i ,a,b)           for(int i=(int)a;i<(int)b;++i)
#define rloop(i,a,b)          for(int i=(int)a;i<=(int)b;++i)
#define loopl(i,a,b)          for(ll i=(ll)a;i<(ll)b;++i)
#define loopr(i,a,b)          for(int i=(int)a;i>=(int)b;--i)
#define count_1(n)            __builtin_popcountll(n)
#define pb                    push_back
#define eb                    emplace_back
#define ab(a)                 (a<0)?(-1*a):a
#define pc                    putchar_unlocked
#define gc                    getchar_unlocked
#define mset(a,b,c)           loop(i,0,b) a[i]=c
#define F                     first
#define S                     second
#define mp                    make_pair
#define clr(x)                x.clear()
#define MOD                   1000000007
#define MAX1                   1e9
#define MIN                   -1e9
#define itoc(c)               ((char)(((int)'0')+c))
#define vi                    vector<int>
#define vvi                   vector<vi>
#define pll                   pair<ll,ll>
#define pii                   pair<int,int>
#define all(p)                p.begin(),p.end()
#define max(x,y)              (x>y)?x:y
#define min(x,y)              (x<y)?x:y
#define mid(s,e)              (s+(e-s)/2)
#define mini                  INT_MIN
#define ifc(i)                (flag[i>>6]&(1<<((i>>1)&31)))
#define isc(i)                (flag[i>>6]|=(1<<((i>>1)&31)))
#define chk(n)                (n==2||(n>2&&(n&1)&&!ifc(n)))
#define sv()                  int t; scanf("%d",&t); while(t--)
using namespace std;
using namespace std::chrono;
#define MAX   1e16;
ll n,a,b,m;

int ch(int ar[], int k)
{
    ll an1 =0, an2 =0;
    for(int i =0;i<n;i++)
    {
       if(ar[i] < k)
        an1 += k - ar[i];
      else if(ar[i] > k)
        an2 += ar[i] - k;
    }
    ll val1 = an1*a + an2*b;
    ll val2 = 0;
    if(an1 >  an2){
      val2 = m*an2;
      val2 += a*(an1 - an2);
    }
    else
    {
      val2 += m*an1;
      val2 += b*(an2 - an1);
    }
    return min(val1, val2);
}
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin>>n>>a>>b>>m;
  int ar[n];
  for(int i =0;i<n;i++)
    cin>>ar[i];
  ll ma = 1e9;
  ll mi = 0;
  ll ans =0;
  while(ma >=  mi)
    {
        int mid = mi + (ma - mi)/2;
        ll val1 = ch(ar, mid-1);
        ll val2 = ch(ar, mid);
        ll val3 = ch(ar, mid+1);
        //cout<<val1<<" "<<val2<<" "<<val3<<"\n";
        //break;

        if(val1 >= val2 && val2 <= val3)
        {
          //cout<<mid<<" ";
           ans = val2;
           break;
        }
        else if(val1 <= val2 && val2 <= val3)
        {
            ma = mid;
        }
        else if(val1 >=  val2 && val2 >= val3)
        {
           mi  = mid;
        }

    }
    cout<<ans<<"\n";

}


    #include<bits/stdc++.h>
    #include<fstream>
    #include <chrono>
    #define ll                    long long int
    #define loop(i ,a,b)           for(int i=(int)a;i<(int)b;++i)
    #define rloop(i,a,b)          for(int i=(int)a;i<=(int)b;++i)
    #define loopl(i,a,b)          for(ll i=(ll)a;i<(ll)b;++i)
    #define loopr(i,a,b)          for(int i=(int)a;i>=(int)b;--i)
    #define count_1(n)            __builtin_popcountll(n)
    #define pb                    push_back
    #define eb                    emplace_back
    #define ab(a)                 (a<0)?(-1*a):a
    #define pc                    putchar_unlocked
    #define gc                    getchar_unlocked
    #define mset(a,b,c)           loop(i,0,b) a[i]=c
    #define F                     first
    #define S                     second
    #define mp                    make_pair
    #define clr(x)                x.clear()
    #define MOD                   1000000007
    #define MAX1                   1e9
    #define MIN                   -1e9
    #define itoc(c)               ((char)(((int)'0')+c))
    #define vi                    vector<int>
    #define vvi                   vector<vi>
    #define pll                   pair<ll,ll>
    #define pii                   pair<int,int>
    #define all(p)                p.begin(),p.end()
    #define max(x,y)              (x>y)?x:y
    #define min(x,y)              (x<y)?x:y
    #define mid(s,e)              (s+(e-s)/2)
    #define mini                  INT_MIN
    #define ifc(i)                (flag[i>>6]&(1<<((i>>1)&31)))
    #define isc(i)                (flag[i>>6]|=(1<<((i>>1)&31)))
    #define chk(n)                (n==2||(n>2&&(n&1)&&!ifc(n)))
    #define sv()                  int t; scanf("%d",&t); while(t--)
    using namespace std;
    using namespace std::chrono;
    #define MAX   1e16;
    ll n,a,b,m;

    ll ch(ll ar[], ll k)
    {
        ll an1 =0, an2 =0;
        for(int i =0;i<n;i++)
        {
           if(ar[i] < k)
            an1 += k - ar[i];
          else if(ar[i] > k)
            an2 += ar[i] - k;
        }

        ll val1 = (an1*a) + (an2*b);
        ll val2 = 0;
        if(an1 >  an2)
        {
          val2 = m*an2;
          val2 += a*(an1 - an2);
        }
        else
        {
          val2 += m*an1;
          val2 += b*(an2 - an1);
        }
        return min(val1, val2);
    }
    int main()
    {
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);
      cin>>n>>a>>b>>m;
      ll ar[n];
      for(int i =0;i<n;i++)
        cin>>ar[i];
      ll ma = 2e9;
      ll mi = 0;
      ll ans =0;
      while(ma >=  mi)
        {
            ll mid = mi + (ma - mi)/2;
            ll val1 = ch(ar, mid-1);
            ll val2 = ch(ar, mid);
            ll val3 = ch(ar, mid+1);
            //cout<<val1<<" "<<val2<<" "<<val3<<"\n";
            //break;
            //cout<<mid<<" "<<val2<<"\n";
            if(val1 >= val2 && val2 <= val3)
            {
              //cout<<mid<<" ";
               ans = val2;
               break;
            }
            else if(val1 <= val2 && val2 <= val3)
            {
                ma = mid;
            }
            else if(val1 >=  val2 && val2 >= val3)
            {
               mi  = mid;
            }

        }
        cout<<ans<<"\n";

    }


#include<bits/stdc++.h>
#include<fstream>
#include <chrono>
#define ll                    long long int
#define loop(i ,a,b)           for(int i=(int)a;i<(int)b;++i)
#define rloop(i,a,b)          for(int i=(int)a;i<=(int)b;++i)
#define loopl(i,a,b)          for(ll i=(ll)a;i<(ll)b;++i)
#define loopr(i,a,b)          for(int i=(int)a;i>=(int)b;--i)
#define count_1(n)            __builtin_popcountll(n)
#define pb                    push_back
#define eb                    emplace_back
#define ab(a)                 (a<0)?(-1*a):a
#define pc                    putchar_unlocked
#define gc                    getchar_unlocked
#define mset(a,b,c)           loop(i,0,b) a[i]=c
#define F                     first
#define S                     second
#define mp                    make_pair
#define clr(x)                x.clear()
#define MOD                   1000000007
#define MAX1                   1e9
#define MIN                   -1e9
#define itoc(c)               ((char)(((int)'0')+c))
#define vi                    vector<int>
#define vvi                   vector<vi>
#define pll                   pair<ll,ll>
#define pii                   pair<int,int>
#define all(p)                p.begin(),p.end()
#define max(x,y)              (x>y)?x:y
#define min(x,y)              (x<y)?x:y
#define mid(s,e)              (s+(e-s)/2)
#define mini                  INT_MIN
#define ifc(i)                (flag[i>>6]&(1<<((i>>1)&31)))
#define isc(i)                (flag[i>>6]|=(1<<((i>>1)&31)))
#define chk(n)                (n==2||(n>2&&(n&1)&&!ifc(n)))
#define sv()                  int t; scanf("%d",&t); while(t--)
using namespace std;
using namespace std::chrono;
#define MAX   1e16;
ll n,a,b,m;

int ch(int ar[], int k)
{
    ll an1 =0, an2 =0;
    for(int i =0;i<n;i++)
    {
       if(ar[i] < k)
        an1 += k - ar[i];
      else if(ar[i] > k)
        an2 += ar[i] - k;
    }
    ll val1 = an1*a + an2*b;
    ll val2 = 0;
    if(an1 >  an2){
      val2 = m*an2;
      val2 += a*(an1 - an2);
    }
    else
    {
      val2 += m*an1;
      val2 += b*(an2 - an1);
    }
    return min(val1, val2);
}
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin>>n>>a>>b>>m;
  int ar[n];
  if(m > a+b)
    m = a+b;
  for(int i =0;i<n;i++)
    cin>>ar[i];
  ll ma = 1e9;
  ll mi = 0;
  ll ans =mi;
  while(ma >= mi)
    {
        int mid = mi + (ma - mi)/2;
        ll val1 = ch(ar, mid-1);
        ll val2 = ch(ar, mid);
        ll val3 = ch(ar, mid+1);
        //cout<<val1<<" "<<val2<<" "<<val3<<"\n";
        if(ma == mi)
        {
           ans = val2;
           break;
        }
        ans = val2;
         if(val1 <= val2 && val2 < val3)
        {
            ma = mid-1;
        }
        else if(val1 >  val2 && val2 >= val3)
        {
           mi  = mid+1;
        }

    }
    cout<<ans<<"\n";

}