15% off all plans & roadmaps Use code
See plansBest Time to Buy and Sell Stock
- LeetCode 121
- Easy
- Dynamic Programming (DP) Patterns
- Stock problems
Updated
TL;DR: Pick one buy day and a later sell day to maximize profit, or return 0. Scan once, track the lowest price seen so far, and record the best gap between today's price and that low.
Problem
You are given an array prices, where prices[i] is the price of a stock on day i.
You may complete one transaction: choose one day to buy a single share and a different, later day to sell it. Return the maximum profit you can make. If no profitable transaction exists, return 0.
Example 1
Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price 1) and sell on day 5 (price 6) for a profit of 6 - 1 = 5. Buying on day 2 and selling on day 1 is not allowed, because the sale must come after the purchase.
Example 2
Input: prices = [7,6,4,3,1] Output: 0 Explanation: Prices only fall, so no transaction makes money. You make none, and the answer is 0.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
Constraints that matter
prices.lengthup to 10^5 rules out checking every buy and sell pair. That is about 5 * 10^9 pairs, far too slow, so you need a linear scan.1 <= prices.lengthmeans the array is never empty, so readingprices[0]is safe. A single price gives no sell day, so the answer is 0.prices[i] >= 0means every difference fits easily in a 32-bit int. The largest possible profit is 10^4, so Java and C# need no long.prices[i] <= 10^4lets you start a running minimum at a large sentinel such as 10^4 + 1 or atprices[0]. Either works without overflow risk.- The answer must be at least 0, so the best-profit variable starts at 0 and never goes negative.
Hints
Hint 1
This is a single pass with a running minimum, the lightest form of the stock-problems DP pattern.
Hint 2
Try every legal transaction.
Solution
Intuition
This is a single pass with a running minimum, the lightest form of the stock-problems DP pattern. The state you carry is tiny: the cheapest price so far and the best profit so far.
Picture walking along a ridge trail and remembering the lowest point you have passed so far. At each step you note how far you have climbed above that low point and keep the biggest climb, so min_price is the remembered low, best is the biggest climb, and you never go back to re-measure earlier spots.
The key observation is about the sell day. Fix a sell day i. The best buy day for it is the cheapest day before i, and nothing else matters. You do not need to compare day i against every earlier day, only against the minimum of them.
So the answer is the maximum over all days i of prices[i] - min(prices[0..i]). Every candidate transaction is covered. Each possible sell day gets its best partner, and the true optimum has some sell day, so the maximum of these values is the optimum.
Order matters because you must buy before you sell. Scanning left to right and updating the minimum as you go enforces that for free. When you reach day i, the minimum you hold only includes days at or before i, so you can never sell before you buy.
A common wrong idea is to take the global minimum and global maximum and subtract. That fails when the maximum comes first, as in [5, 1]. The scan avoids this because it never pairs a price with a low that appears later.
Worked example
Input: prices = [3, 8, 1, 9, 2, 10, 1, 11] Output: 10 Explanation: The lowest price is 1, and the highest price after a 1 is 11 on the last day. Buying at 1 and selling at 11 gives 10. Buying at 3 and selling at 11 gives only 8, so a later, lower buy day wins.
Approach 1: Brute force
Try every legal transaction. For each buy day i, try every sell day j after it, compute prices[j] - prices[i], and keep the largest value. Start the answer at 0 so a falling market returns 0.
This is correct because it enumerates every allowed pair. You can write it in a minute, and it is the baseline to improve.
Steps
- Set
best = 0. - For each buy day
ifrom 0 to n - 1, loop over each sell dayjfrom i + 1 to n - 1. - Compute
profit = prices[j] - prices[i]. - If
profit > best, setbest = profit. - After both loops finish, return
best.
Dry run
On [3, 8, 1, 9, 2, 10, 1, 11] the outer loop picks each buy day in turn and the inner loop finds the best sell price after it.
| Buy day i | Price | Best later price | Best profit for this buy | Running best |
|---|---|---|---|---|
| 0 | 3 | 11 | 8 | 8 |
| 1 | 8 | 11 | 3 | 8 |
| 2 | 1 | 11 | 10 | 10 |
| 3 | 9 | 11 | 2 | 10 |
| 4 | 2 | 11 | 9 | 10 |
| 5 | 10 | 11 | 1 | 10 |
| 6 | 1 | 11 | 10 | 10 |
| 7 | 11 | none | 0 | 10 |
The final running best is 10.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Let n be the length of prices. The outer loop runs n times and the inner loop runs n - 1 - i times for buy day i. The total number of pairs is n * (n - 1) / 2, which is O(n^2). With n = 10^5 that is about 5 * 10^9 comparisons, too slow for typical limits. Only a few integer variables are stored, so space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
best = 0
for i in range(n):
for j in range(i + 1, n):
profit = prices[j] - prices[i]
if profit > best:
best = profit
return best
JavaTested in our runner
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int best = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int profit = prices[j] - prices[i];
if (profit > best) {
best = profit;
}
}
}
return best;
}
}
C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int best = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int profit = prices[j] - prices[i];
if (profit > best) {
best = profit;
}
}
}
return best;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
const n = prices.length;
let best = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
const profit = prices[j] - prices[i];
if (profit > best) {
best = profit;
}
}
}
return best;
};
GoTested in our runner
func maxProfit(prices []int) int {
n := len(prices)
best := 0
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
profit := prices[j] - prices[i]
if profit > best {
best = profit
}
}
}
return best
}
C#Tested in our runner
public class Solution {
public int maxProfit(int[] prices) {
int n = prices.Length;
int best = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int profit = prices[j] - prices[i];
if (profit > best) {
best = profit;
}
}
}
return best;
}
}
Approach 2: Prefix minimum array
What's slow: the inner loop re-scans every later day for each buy day. Most of that work repeats, because for a given sell day only the cheapest earlier price matters.
The insight that fixes it: precompute low[i], the minimum of prices[0..i], in one pass using low[i] = min(low[i-1], prices[i]). Then the best profit for selling on day i is prices[i] - low[i]. A second pass takes the maximum of those values. This is the DP form: each entry is built from the previous entry in constant time.
Steps
- Create an array
lowof the same length asprices. - Set
low[0] = prices[0]. - For i from 1 to n - 1, set
low[i] = min(low[i-1], prices[i]). - Set
best = 0. - For each i, compute
prices[i] - low[i]and keep the larger of it andbest. - Return
best.
Dry run
On [3, 8, 1, 9, 2, 10, 1, 11] the first pass builds low = [3, 3, 1, 1, 1, 1, 1, 1].
The second pass subtracts: 3-3=0, 8-3=5, 1-1=0, 9-1=8, 2-1=1, 10-1=9, 1-1=0, 11-1=10. The largest value is 10, which is the answer.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of prices. The first loop does one min comparison per index and the second does one subtraction and comparison per index. The work is 2n constant-time steps, which is O(n). The low array holds n integers, so space is O(n). The array is not needed, as the next approach shows.
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
low = [0] * n
low[0] = prices[0]
for i in range(1, n):
low[i] = min(low[i - 1], prices[i])
best = 0
for i in range(n):
best = max(best, prices[i] - low[i])
return best
JavaTested in our runner
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[] low = new int[n];
low[0] = prices[0];
for (int i = 1; i < n; i++) {
low[i] = Math.min(low[i - 1], prices[i]);
}
int best = 0;
for (int i = 0; i < n; i++) {
best = Math.max(best, prices[i] - low[i]);
}
return best;
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
vector<int> low(n);
low[0] = prices[0];
for (int i = 1; i < n; i++) {
low[i] = min(low[i - 1], prices[i]);
}
int best = 0;
for (int i = 0; i < n; i++) {
best = max(best, prices[i] - low[i]);
}
return best;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
const n = prices.length;
const low = new Array(n);
low[0] = prices[0];
for (let i = 1; i < n; i++) {
low[i] = Math.min(low[i - 1], prices[i]);
}
let best = 0;
for (let i = 0; i < n; i++) {
best = Math.max(best, prices[i] - low[i]);
}
return best;
};
GoTested in our runner
func maxProfit(prices []int) int {
n := len(prices)
low := make([]int, n)
low[0] = prices[0]
for i := 1; i < n; i++ {
low[i] = low[i-1]
if prices[i] < low[i] {
low[i] = prices[i]
}
}
best := 0
for i := 0; i < n; i++ {
if prices[i]-low[i] > best {
best = prices[i] - low[i]
}
}
return best
}
C#Tested in our runner
public class Solution {
public int maxProfit(int[] prices) {
int n = prices.Length;
int[] low = new int[n];
low[0] = prices[0];
for (int i = 1; i < n; i++) {
low[i] = Math.Min(low[i - 1], prices[i]);
}
int best = 0;
for (int i = 0; i < n; i++) {
best = Math.Max(best, prices[i] - low[i]);
}
return best;
}
}

Solution pattern
Stock problems
Approach 3: One pass with running minimumOptimalStock problems
What's slow: the prefix array stores n values, yet each step reads only the previous entry. The memory is wasted, and two passes are unnecessary.
The insight that fixes it: merge both loops and keep a single variable min_price instead of the array. At each day, first test whether selling today beats best, then lower min_price if today is cheaper. One loop, two variables. You can also see this as a sliding window: the left edge is the buy day, the right edge is the sell day, and the left edge jumps to the right edge whenever a new low appears.
Steps
- Set
min_price = prices[0]andbest = 0. - Loop over each
priceinprices. - If
price < min_price, setmin_price = price, because a cheaper buy day appeared. - Otherwise compute
price - min_priceand updatebestif it is larger. - Return
bestafter the loop.
Dry run
Trace on [3, 8, 1, 9, 2, 10, 1, 11]. The candidate column is price - min_price using the minimum after processing that day.
| Day | Price | min_price after | Candidate | best after |
|---|---|---|---|---|
| 0 | 3 | 3 | 0 | 0 |
| 1 | 8 | 3 | 5 | 5 |
| 2 | 1 | 1 | 0 | 5 |
| 3 | 9 | 1 | 8 | 8 |
| 4 | 2 | 1 | 1 | 8 |
| 5 | 10 | 1 | 9 | 9 |
| 6 | 1 | 1 | 0 | 9 |
| 7 | 11 | 1 | 10 | 10 |
The loop ends with best = 10, which matches the expected output. On day 2 the price 1 becomes the new buy day, and every later sale is measured against it.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the length of prices. The loop runs exactly n times and each iteration does one comparison, at most one subtraction and one assignment, so time is O(n). Only min_price and best are stored, independent of n, so space is O(1). This is optimal for time because any correct answer must read every price at least once.
PythonTested in our runner
from typing import List, Optional
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price = prices[0]
best = 0
for price in prices:
if price < min_price:
# a cheaper buy day for all later sales
min_price = price
elif price - min_price > best:
best = price - min_price
return best
JavaTested in our runner
class Solution {
public int maxProfit(int[] prices) {
int minPrice = prices[0];
int best = 0;
for (int price : prices) {
if (price < minPrice) {
// a cheaper buy day for all later sales
minPrice = price;
} else if (price - minPrice > best) {
best = price - minPrice;
}
}
return best;
}
}
C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int minPrice = prices[0];
int best = 0;
for (int price : prices) {
if (price < minPrice) {
// a cheaper buy day for all later sales
minPrice = price;
} else if (price - minPrice > best) {
best = price - minPrice;
}
}
return best;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let minPrice = prices[0];
let best = 0;
for (const price of prices) {
if (price < minPrice) {
// a cheaper buy day for all later sales
minPrice = price;
} else if (price - minPrice > best) {
best = price - minPrice;
}
}
return best;
};
GoTested in our runner
func maxProfit(prices []int) int {
minPrice := prices[0]
best := 0
for _, price := range prices {
if price < minPrice {
// a cheaper buy day for all later sales
minPrice = price
} else if price-minPrice > best {
best = price - minPrice
}
}
return best
}
C#Tested in our runner
public class Solution {
public int maxProfit(int[] prices) {
int minPrice = prices[0];
int best = 0;
foreach (int price in prices) {
if (price < minPrice) {
// a cheaper buy day for all later sales
minPrice = price;
} else if (price - minPrice > best) {
best = price - minPrice;
}
}
return best;
}
}
Common mistakes
- Subtracting
min(prices)frommax(prices). The minimum can come after the maximum, as in[5, 1], which would give 4 instead of 0. Pair each sell day only with a low from earlier days. - Starting
bestatfloat('-inf'),Integer.MIN_VALUEorprices[0] - prices[1]. The problem says to return 0 when no profit exists, so startbest = 0and let it only grow. - Updating
min_pricewithprices[i]before computing the profit and then using the same day as both buy and sell. That gives 0 for that day, which is harmless, but in a version that tracks indexes it can allow same-day trades. Compute the candidate from the minimum of earlier days or accept the 0. - Initializing
min_price = 0. Then every price minus 0 equals the price itself and the answer becomes the maximum price. Start fromprices[0]or a large sentinel likefloat('inf')orINT_MAX. - Running nested loops and expecting them to pass. With 10^5 prices that is about 5 * 10^9 pair checks, which times out. Replace the inner loop with the running minimum.
- Resetting
bestwhen a new minimum appears. A new low only changes the future buy price, and profits already found remain valid. Keepbestuntouched in that branch.
Edge cases
[5]: one day, no sell day exists. Return 0.[7, 6, 4, 3, 1]: strictly decreasing, so no profit is possible. Return 0.[1, 2, 3, 4, 5]: strictly increasing. Buy on the first day and sell on the last for 4.[2, 2, 2, 2]: all equal prices give differences of 0. Return 0.[5, 1]or[10, 1, 2]: the global max comes before the global min. The answer must come from the later segment, here 0 and 1.[0, 10000]and an array of 10^5 prices: the largest value is 10^4 and fits in an int, and the scan must finish in linear time.
Follow-ups interviewers ask
- What if you may complete as many transactions as you like (Best Time to Buy and Sell Stock II)?
- Capture every upward step. Sum
max(0, prices[i] - prices[i-1])over all days. This works because any multi-day rise equals the sum of its daily rises, and you skip every fall. It runs in O(n) time and O(1) space. - How would you also return the buy day and sell day, not only the profit?
- Track the index of the current minimum alongside its value. When a candidate beats
best, record the stored minimum index as the buy day and the current index as the sell day. The loop stays O(n) and the extra state is three integers. - What if you may make at most two or at most k transactions?
- A single running minimum is no longer enough, so you track a state per transaction. For two transactions keep
buy1,sell1,buy2andsell2and update them in order each day. For k transactions use a DP table of size k by n, or k by 2 with rolling state, giving O(n * k) time.
Best Time to Buy and Sell Stock FAQ
What is the time complexity of Best Time to Buy and Sell Stock?
The optimal one-pass solution is O(n) time and O(1) space, where n is the number of days. The brute force version is O(n^2) because it checks every buy and sell pair. The prefix minimum array version is O(n) time and O(n) space.
Why use a running minimum for Best Time to Buy and Sell Stock?
For any sell day, the best buy day is the cheapest day before it. A running minimum gives that value in constant time, so each day needs one subtraction instead of a scan over all earlier days. That turns O(n^2) into O(n).
Can Best Time to Buy and Sell Stock be solved in O(1) extra space?
Yes. The one-pass solution stores only min_price and best. The prefix minimum array is only a stepping stone and can be dropped because each entry depends only on the previous one.
Is LeetCode 121 a dynamic programming, greedy or sliding window problem?
It fits all three views. The DP view says the best profit ending on day i depends on the minimum up to day i. The greedy view says to keep the cheapest buy so far. The sliding window view moves the left edge to the right edge on each new low. The code is identical.
What should I return if the prices only go down?
Return 0. The problem lets you skip the transaction, so negative profit is never reported. Initializing best = 0 handles this without a special case.
When should I buy and sell shares in real life, and what are the 7% sell rule and 10am rule?
This problem is not trading advice. It assumes you already know every future price, so the best buy and sell days are knowable. Real markets give no such information. The 7% sell rule and the 10am rule are trader rules of thumb, and nothing in the LeetCode solution depends on them.
Asked at
See which companies ask this — Pro
Related problems
- Best Time to Buy and Sell Stock with Cooldown · same technique: Stock problems
- Best Time to Buy and Sell Stock II · same technique: Stock problems
- Best Time to Buy and Sell Stock III · same technique: Stock problems
- Meeting Rooms · same pattern: Dynamic Programming (DP) Patterns
- Climbing Stairs · same pattern: Dynamic Programming (DP) Patterns
- Min Cost Climbing Stairs · same pattern: Dynamic Programming (DP) Patterns
- Lemonade Change · same pattern: Dynamic Programming (DP) Patterns
- N-th Tribonacci Number · same pattern: Dynamic Programming (DP) Patterns
- Fibonacci Number · same pattern: Dynamic Programming (DP) Patterns
- Assign Cookies · same pattern: Dynamic Programming (DP) Patterns