prices[j] - prices[i]
where i
is the buy day and j
is the sell day (with j > i
).i
as the buying day.i
, we iterate over all subsequent days j
(where j > i
) as the selling day.prices[j] - prices[i]
.j
is higher than on day i
), we check if this profit is the highest profit seen so far.max_profit
will be the answer.
The brute-force solution checks every possible pair of buy and sell days using nested loops, leading to:
The optimal solution uses a single pass to track the minimum price seen so far, achieving O(n) time complexity:
The “Best Time to Buy and Sell Stock” problem is one of the most fundamental algorithm questions involving arrays and financial profit optimization.
Given an array of stock prices where prices[i]
represents the stock price on the ith
day, your goal is to determine the maximum profit you can achieve by making one buy and one sell.
You must buy before you sell.
This problem teaches a key concept in algorithm design: finding optimal values while scanning a sequence only once. It demonstrates how to convert a seemingly quadratic-time problem into an efficient linear-time solution using a greedy approach and running minimum tracking.
A straightforward solution is to consider every possible pair of days (i, j) such that i < j
. For each pair, you compute the profit prices[j] - prices[i]
, and track the maximum profit.
This approach works correctly but is inefficient for large inputs due to its nested loop structure.
Time Complexity: O(n²)
Space Complexity: O(1)
Instead of checking every pair, we can achieve an optimal solution in O(n) time using a single pass. The main idea is to:
This greedy strategy ensures that we always buy at the lowest price and sell later at the highest price that gives the best return.
Suppose we have the array prices = [7, 1, 5, 3, 6, 4]
. Let’s walk through it:
min_price = 7
, no profit yet.min_price = 1
max_profit = 4
max_profit = 5
The final answer is 5, which is the maximum profit possible from buying on day 1 (price 1) and selling on day 4 (price 6).
[7,6,4,3,1]
), no profit is possible → return 0.
Time Complexity: O(n), where n is the length of the prices array. We make only a single pass through the array.
Space Complexity: O(1), since we use only two variables: min_price
and max_profit
.
The “Best Time to Buy and Sell Stock” problem is a classic example of optimizing over a sequence using minimal memory and maximum efficiency. It introduces critical techniques like maintaining a running minimum and calculating deltas on the fly — useful skills in both interviews and real-world algorithmic problems.