#C3324. Maximum Stock Profit

    ID: 46739 Type: Default 1000ms 256MiB

Maximum Stock Profit

Maximum Stock Profit

You are given a list of stock prices, where the i-th element represents the price on day \(i+1\). Your task is to compute the maximum profit that can be achieved from a single buy and a single sell transaction. In other words, you need to find two indices \(i\) and \(j\) such that \(i < j\) and the difference \(prices[j] - prices[i]\) is maximized. If no profitable transaction is possible, output 0.

This can be formally expressed as: \[ \text{max\_profit} = \max_{0 \le i < j < n}\{prices[j] - prices[i]\} \]

If the list is empty or if no profit can be made, the answer is \(0\).

inputFormat

The input is read from stdin and has the following format:

T
n
prices[0] prices[1] ... prices[n-1]
... (repeated T times)

Where:

  • T is the number of test cases.
  • For each test case, the first line contains an integer n specifying the number of days, and the second line contains n space-separated integers representing the stock prices.

outputFormat

For each test case, output a single integer representing the maximum profit achievable, each on a new line, to stdout.

## sample
2
6
7 1 5 3 6 4
5
7 6 4 3 1
5

0

</p>