You are given the price of one stock on each of a sequence of days: prices[i] is the price on day i. You may buy one share on some day and sell it on a strictly later day, at most once. Return the largest profit you can make. If no buy-then-sell pair makes money, you do not trade and the profit is 0.
Function Signature
def max_single_trade_profit(prices: list[int]) -> int:
Rules
-
Buying on day
i
and selling on day
j
earns
prices[j] - prices[i]
, and requires
i < j
. You cannot sell before you buy.
-
At most one buy and one sell in total. Not trading is always allowed, so the answer is never negative.
-
Return only the profit, which is unique even when several pairs of days achieve it.
Constraints
-
1 <= len(prices) <= 100000
-
0 <= prices[i] <= 10000
-
The answer is an integer between 0 and 10000.
Examples
Example 1
Input: prices = [9, 4, 6, 3, 8, 5]
Output: 5
Buy on day 3 at price 3 and sell on day 4 at price 8. Buying at 4 and selling at 8 would earn only 4.
Example 2
Input: prices = [10, 8, 5, 5, 1]
Output: 0
The price never rises from any day to a later day, so the best choice is not to trade.
Example 3
Input: prices = [7]
Output: 0
With a single day there is no later day to sell on.