AceYourInterviews
Checking sign-in…

146. Best Time to Buy and Sell Stock — One Transaction

StarterDominance of the cheapest strictly earlier buy price

Choose a day to buy one share and a strictly later day to sell it. Maximize the selling price minus the buying price, or choose no transaction when no profitable pair exists.

A sell day cannot precede or equal the buy day. This version permits at most one transaction and returns zero rather than a negative loss.

Example 1

Input

prices=[7,1,5,3,6,4]

Output

5

Explanation: Buy at one on day one and sell at six on day four.

Example 2

Input

prices=[7,6,4,3,1]

Output

0

Explanation: Every legal transaction loses; doing nothing wins.

Example 3

Input

prices=[2,4,1]

Output

2

Explanation: The cheapest overall price occurs too late to buy for the earlier sale.

Constraints

  • 0 <= prices.length <= 105
  • 0 <= prices[i] <= 231 - 1
Hints
Hint 1

If the selling day is fixed, which earlier buying price is best?

Hint 2

Can any higher earlier price beat the prefix minimum on a future sale?

Hint 3

Evaluate today’s sale against the old minimum, update the best, then include today in the minimum.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Preserve earlier profit while updating buying opportunities

[7,1,5,3,6,4]
5