#C12839. Maximum Profit in Stock Trading

    ID: 42310 Type: Default 1000ms 256MiB

Maximum Profit in Stock Trading

Maximum Profit in Stock Trading

You are given an array of integers representing the stock price on each day. Your task is to compute the maximum profit you can achieve by buying on one day and selling on a later day. If no profit is possible, return 0.

More formally, given an array of prices, you need to find two indices \(i\) and \(j\) such that \(i < j\) and the profit \(price_j - price_i\) is maximized. That is, $$ \text{profit} = price_{sell} - price_{buy} $$ If no such pair exists that yields a positive profit, the answer should be 0.

Input Format: The first line contains an integer \(n\) representing the number of days. The second line contains \(n\) space-separated integers where each integer corresponds to the stock price on that day.

Output Format: Output a single integer which is the maximum profit achievable. If no profit can be made, output 0.

inputFormat

The input 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.

outputFormat

Output a single integer which is the maximum profit that can be obtained by buying and selling once. If no profit is possible, output 0.

## sample
6
7 1 5 3 6 4
5