Back to problems Sign in to unlock
Leetcode
Easy
Arrays
Greedy
Dynamic Programming
Amazon
Microsoft
Best Time To Buy And Sell Stock
Find the maximum profit from one buy and one sell of a stock over a sequence of daily prices.
Acceptance 82%
Problem Statement
Problem
You are given an array prices where prices[i] is the stock price on day i.
You may complete at most one transaction: buy one share on one day and sell that share on a later day.
Return the maximum profit you can achieve. If no profitable transaction exists, return 0.
Notes
- You must buy before you sell.
- You can only hold one share at a time.
- If prices never rise after a buy day, the best action is to do nothing.
Input Format
- A single integer array
prices. prices[i]represents the stock price on dayi.
Output Format
- Return a single integer: the maximum possible profit from one buy/sell transaction.
Constraints
1 <= prices.length- Prices are non-negative integers.
- You may make at most one buy and one sell.
- The sell day must be strictly after the buy day.
Examples
Sample cases returned by the problem API.
Example 1
Input
prices = [7,1,5,3,6,4]
Output
5
Explanation
Buy on day 2 at price 1 and sell on day 5 at price 6 for a profit of 5.
Example 2
Input
prices = [7,6,4,3,1]
Output
0
Explanation
Prices only decrease, so no profitable transaction exists.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.
Guided hints
Editorial and discussion links
Concept map and variants
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.