All problems

Problem 28

Best Time to Buy and Sell Stock

Easy · 10 pts · Array, Greedy

Problem

You are given the price of a stock on each of N days. You may make at most one trade: buy one share on some day and sell it on a later day. Find the largest profit you can make, which is the selling price minus the buying price. If prices only go down, no trade makes money, and the answer is 0 (you simply do not trade). Scan the days from left to right, remember the lowest price seen so far, and at each day check the profit of selling at today's price.

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the maximum profit.

Constraints

1 <= N <= 100000; 0 <= price[i] <= 10000

Example input

6
7 1 5 3 6 4

Example output

5

Explanation

The prices are 7 1 5 3 6 4. Buying on day 2 at price 1 and selling on day 5 at price 6 gives 6 - 1 = 5. No other pair of days does better, so the answer is 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Majority Element Next: Best Time to Buy and Sell Stock II