Best Time to Buy and Sell Stock Solution
Given an array prices where prices[i] is the price on day i, return the maximum profit from one buy and one sell.
Problem Statement
You are given an array prices where prices[i] is the price of a stock on day i. You want to maximize profit by choosing a single day to buy and a single future day to sell. Return the maximum profit, or 0 if no profit is possible.
Brute Force โ O(nยฒ)
For every day i, check every future day j > i and compute prices[j] - prices[i]. Track the maximum difference.
prices[i] - minSoFar. One pass, O(1) space.
| Metric | Value |
|---|---|
| Time | O(nยฒ) |
| Space | O(1) |
One Pass โ O(n)
Scan left to right, tracking the minimum price seen so far. At each day, compute profit as price - minPrice. Update the maximum profit. The minimum price acts as the left pointer of a sliding window โ it resets whenever a cheaper buy opportunity is found.
- Step 1:
minPrice = โ,maxProfit = 0. - Step 2: For each price: update
minPrice = min(minPrice, price). - Step 3: Update
maxProfit = max(maxProfit, price - minPrice). - Step 4: Return
maxProfit.
- Any problem asking for the maximum difference between two elements where the smaller must come first โ think track-min-so-far.
- This is a degenerate sliding window where the left boundary only moves forward when a new minimum is found.
- The same idea extends to maximum subarray (Kadane's algorithm) and stock problems with multiple transactions.
Visual Walkthrough
Trace through prices = [7, 1, 5, 3, 6, 4]:
Code โ Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Brute Force | O(nยฒ) | O(1) | Check all buy/sell pairs |
| One Pass โ optimal | O(n) | O(1) | Track min price, compute profit at each step |
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Decreasing prices | [7, 6, 4, 3, 1] | No profit possible โ return 0. Profit is never positive. |
| Single day | [5] | Can't buy and sell on same day โ 0. |
| All same price | [3, 3, 3] | Profit = 0 everywhere. |
| Best at end | [2, 4, 1, 7] | Min shifts to 1 on day 2, best profit at day 3: 7-1=6. |
| Best at start | [1, 5, 2, 3] | Min stays 1, best profit is 5-1=4 on day 1. |
max(prices) - min(prices) without checking that the min comes before the max. The minimum price might occur after the maximum, making the trade impossible. Tracking minSoFar as you scan left-to-right guarantees you only consider valid buy-before-sell pairs.