#K54017. Maximum Stock Profit

    ID: 29660 Type: Default 1000ms 256MiB

Maximum Stock Profit

Maximum Stock Profit

You are given a sequence of integers representing the price of a stock for consecutive days. Your task is to determine the maximum profit achievable by buying on one day and selling on a later day. In other words, given an array of prices, you need to find two indices (i) and (j) such that (i < j) and (prices[j] - prices[i]) is maximized. If no profit can be made, return 0.

Formally, if the stock prices over (n) days are given by an array (P = [p_1, p_2, \ldots, p_n]), you must compute

[ \max_{1 \leq i < j \leq n} (p_j - p_i) \quad \text{or} \quad 0 \text{ if } p_j \leq p_i \text{ for all } i < j. ]

Note that you are allowed only one transaction (one buy and one sell).

inputFormat

The input is read from the standard input. The first line contains an integer (n) representing the number of days. The second line contains (n) space-separated integers representing the stock prices for these days. If (n = 0), the stock prices list is empty.

outputFormat

Output a single integer representing the maximum profit possible. If no profit can be made, output 0.## sample

6
7 1 5 3 6 4
5

</p>