Show problems as
Classic problem #121EasyArrayDynamic Programming

Best Time to Buy and Sell Stock

Real-world version: One Flip on the Card Market
Tracked in this browser only
Read Best Time to Buy and Sell Stock on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A collectors' marketplace publishes one closing quote per trading session for a single rare card. You are given the integer array quotes, which lists those closing quotes in session order.

You may complete at most one round trip on that card: acquire it at the quote of some session, then release it at the quote of a session that lands strictly later. The gain of a round trip is its release quote minus its acquisition quote.

Return the largest gain any single round trip can reach. When no session is quoted above any session that precedes it, no round trip can finish ahead, so staying out of the market is optimal and the answer is 0.

Examples

Example 1

Input
quotes = [9, 4, 6, 3, 8, 5]
Output
5

The lowest quote available is the 3 in session 3, and the highest quote after it is the 8 in session 4, a spread of 5. No other ordered pair of sessions spreads wider.

Example 2

Input
quotes = [12, 11, 9, 6]
Output
0

Each session is quoted under the one before it, so any completed round trip destroys value and sitting out wins.

Example 3

Input
quotes = [3]
Output
0

One session leaves nothing to release into, so no round trip is possible.

Constraints

  • 1 <= quotes.length <= 10^5
  • 0 <= quotes[i] <= 10^4

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def max_flip_gain(quotes: list[int]) -> int:
Java
public int maxFlipGain(int[] quotes)