Skip to content

Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

InputOutputExplanation
[7, 1, 5, 3, 6, 4]5Buy at day 1 (price = 1), sell at day 4 (price = 6), profit = 6 - 1 = 5
[7, 6, 4, 3, 1]0Prices are falling. No profit is possible.
[2, 4, 1, 7, 5, 11]9Buy at day 0 (price = 2), sell at day 5 (price = 11), profit = 11 - 2 = 9
  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
ApproachTimeSpaceBest When
Single PassO(n)O(1)General case — fast, memory-efficient, tracks min price
Brute ForceO(n²)O(1)Learning the pattern, arrays are very small
  • Pick Single Pass for the optimal solution — it is straightforward and O(n).
  • Pick Brute Force if you are just starting to understand the problem or need to explain the idea simply.
Best For Speed
Single Pass
O(n) time · O(1) space
Simple to Learn
Brute Force
O(n²) time · O(1) space

Approach 1: Single Pass with Min Price Tracking

Section titled “Approach 1: Single Pass with Min Price Tracking”
★ Recommended

Keep track of the lowest price seen so far as you iterate through the prices. At each day, calculate the profit if you sell at that day’s price. Update the maximum profit whenever a better profit is found.

The key insight is that the best selling day for any given price is always after the minimum price we have seen. By scanning left to right, we ensure the buy day always comes before the sell day.

⏱ Time O(n) Single pass, no extra structures 💾 Space O(1) Only two variables

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

DayPriceMin Price SeenProfit if Sell TodayMax Profit
0770
1111 - 1 = 00
2515 - 1 = 44
3313 - 1 = 24
4616 - 1 = 55
5414 - 1 = 35

Animated walkthrough

How single pass finds the maximum profit

Use Next or Autoplay to watch the minimum price and maximum profit update as you scan through the prices.

Step 1 of 6
Waiting to begin...
Array state
Memory / lookup state

function maxProfitSinglePass(prices):
if prices.length < 2:
return 0
minPrice = prices[0]
maxProfit = 0
for i from 1 to len(prices) - 1:
profit = prices[i] - minPrice
maxProfit = max(maxProfit, profit)
minPrice = min(minPrice, prices[i])
return maxProfit
best_time_to_buy_and_sell_stock_single_pass.py
# Approach: Single Pass with Min Price Tracking
# Track the minimum price seen so far and calculate the maximum profit at each price.
# When we see a new price, we check the profit if we sell at that price.
#
# Time Complexity: O(n) — single pass
# Space Complexity: O(1)
from typing import List
def max_profit(prices: List[int]) -> int:
if not prices or len(prices) < 2:
return 0
min_price = prices[0]
max_profit_val = 0
for price in prices[1:]:
profit = price - min_price
max_profit_val = max(max_profit_val, profit)
min_price = min(min_price, price)
return max_profit_val
print(max_profit([7, 1, 5, 3, 6, 4])) # 5
print(max_profit([7, 6, 4, 3, 1])) # 0
print(max_profit([2, 4, 1, 7, 5, 11])) # 9
✓ Simple

For each pair of days (i, j) where i < j, calculate the profit as prices[j] - prices[i] and track the maximum. This is the most direct method but becomes slow for large arrays.

⏱ Time O(n²) All pairs checked 💾 Space O(1) No extra memory

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

Buy DaySell DayBuy PriceSell PriceProfit
0171-6
0275-2
0373-4
0476-1
0574-3
12154
13132
14165
15143
function maxProfitBruteForce(prices):
n = len(prices)
maxProfit = 0
for i from 0 to n - 1:
for j from i + 1 to n - 1:
profit = prices[j] - prices[i]
maxProfit = max(maxProfit, profit)
return maxProfit
best_time_to_buy_and_sell_stock_brute_force.py
# Approach: Brute Force
# Try every pair (i, j) where i < j. Profit = prices[j] - prices[i].
# Track the maximum profit across all pairs.
#
# Time Complexity: O(n²) — nested loops over all pairs
# Space Complexity: O(1)
from typing import List
def max_profit(prices: List[int]) -> int:
n = len(prices)
max_profit_val = 0
for i in range(n):
for j in range(i + 1, n):
profit = prices[j] - prices[i]
max_profit_val = max(max_profit_val, profit)
return max_profit_val
print(max_profit([7, 1, 5, 3, 6, 4])) # 5
print(max_profit([7, 6, 4, 3, 1])) # 0
print(max_profit([2, 4, 1, 7, 5, 11])) # 9
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
best_time_to_buy_and_sell_stock_space_optimized.py
"""
Solution for Best Time to Buy and Sell Stock
"""
def solve():
"""Implementation for approach 3 of Best Time to Buy and Sell Stock"""
pass
if __name__ == "__main__":
print("Solution ready")