146. Best Time to Buy and Sell Stock — One Transaction
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 <= 1050 <= 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.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Preserve earlier profit while updating buying opportunities
[7,1,5,3,6,4]
5