#K75512. Maximum Stock Profit
Maximum Stock Profit
Maximum Stock Profit
You are given a sequence of daily stock prices. Your task is to determine the maximum profit you can achieve by choosing a day to buy and a later day to sell. In formal terms, if the array of prices is \(P = [p_1, p_2, \dots, p_n]\), you need to compute:
[ \max_{1 \leq i < j \leq n} (p_j - p_i) ]
If no profit can be made (i.e. the prices only fall or remain constant), output 0.
Example:
- For
[7, 1, 5, 3, 6, 4]
, the maximum profit is 5 (buy at 1 and sell at 6). - For
[9, 7, 5, 3, 1]
, the maximum profit is 0.
inputFormat
The input is read from standard input (stdin) and consists of two lines:
- The first line contains a single integer \(n\), the number of days.
- The second line contains \(n\) space-separated integers representing the stock prices for each day.
outputFormat
Output a single integer to standard output (stdout), which is the maximum profit achievable. If no profit can be made, output 0.
## sample6
7 1 5 3 6 4
5
</p>