using System;

class TEST
{
    public static void Main()
    {
        long num = long.Parse(Console.ReadLine());
        string[] str = Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
        long[] people = new long[num];
        long[] sabun = new long[num];

        for (int i = 0; i < num; i++)
        {
            people[i] = long.Parse(str[i]);
            sabun[i] = 0;
        }
  //      while (true)
//        {
     //   YAHOO:
            for (int i = 1; i < num; i++)
            {
                int value = (people[i] + sabun[i]) - (people[i - 1] + sabun[i - 1]);
                if (value < 0)
                {
                    sabun[i] -= value;
                 //   sabun[i]++;
                  //  goto YAHOO;
                }
   //         }
     //       break;
        }

        int ans = 0;
        foreach (long value in sabun)
        {
            ans += value;
        }
        Console.WriteLine(ans);
         //   Console.ReadKey();
    }

}