Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1

Solution in C# (judge verdict: Accepted)

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("6");
            WillReturn.Add("5");
            WillReturn.Add("3");
            WillReturn.Add("1");
            WillReturn.Add("3");
            WillReturn.Add("4");
            WillReturn.Add("3");
            //3
            //価格が1のとき買って
            //4のときに売ると4-1=3で最大3の利益を得ることができます。
            //最初の5を使うと5-1=4となりますが、
            //これは5の方が時間が前なので許されません。
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("3");
            WillReturn.Add("4");
            WillReturn.Add("3");
            WillReturn.Add("2");
            //-1
            //価格が減少しているケースですが、
            //この問題ではJ > I という条件から、
            //買って売る作業を1回は行う必要があるので、
            //最大利益は-1となります。
        }
        else if (InputPattern == "Input3") { //最悪計算量
            WillReturn.AddRange(Enumerable.Repeat("100000000", 200000));
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        int[] R = InputList.Skip(1).Select(X => int.Parse(X)).ToArray();

        int MinValue = R[0]; //最小価格
        int MaxProfit = int.MinValue; //最大利益

        for (int I = 1; I <= R.GetUpperBound(0); I++) {
            int CurrProfit = R[I] - MinValue;

            //最大利益の更新
            if (MaxProfit < CurrProfit)
                MaxProfit = CurrProfit;

            //最小価格の更新
            if (MinValue > R[I])
                MinValue = R[I];
        }
        Console.WriteLine(MaxProfit);
    }
}