#K79337. Maximum Stock Profit
Maximum Stock Profit
Maximum Stock Profit
You are given a sequence of stock prices over consecutive days. Your task is to determine the maximum profit you can achieve by performing a single buy-sell operation. If no profit can be made (i.e. the prices are strictly decreasing or all equal) you should output 0. If the list is empty or contains only one price, output -1.
Formally, given a sequence \(P = [P_1, P_2, \dots, P_n]\), you need to find the maximum value of \(P_j - P_i\) for \(1 \le i < j \le n\). If \(n < 2\), output \(-1\).
inputFormat
The input is read from the standard input (stdin) in the following format:
- The first line contains an integer
n
which denotes the number of days (prices). - If
n > 0
, the second line containsn
space-separated integers representing the stock prices.
If n
is 0, then no prices are provided.
outputFormat
Output a single integer, the maximum profit that can be achieved by buying and then selling one stock. Output -1
if the list of prices is empty or contains only one element.
5
1 2 3 4 5
4