Best Time to Buy and Sell Stock
What the problem is really asking
We are allowed exactly one buy and one sell.
So the real question is:
"For every day I could sell, what is the cheapest day I could have bought before it?"
Intuition
If today is the selling day, then only one thing matters from the past: the lowest price seen so far.
That means we do not need to remember every earlier price. We only need the best buying opportunity up to this point.
Brute-force idea
The direct solution is to try every pair of days:
- buy on day
i - sell on day
j > i - compute the profit
- keep the maximum
That works, but it takes O(n^2) time.
Optimized approach
Walk through the array once:
- keep
minPrice, the cheapest stock price seen so far - at each day, pretend we sell today
- profit would be
currentPrice - minPrice - update the best answer
Then move on.
This works because the best sale ending today must use the cheapest earlier buying price.
Code Solution
Switch between languages
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int bestProfit = 0;
for (int price : prices) {
minPrice = Math.min(minPrice, price);
bestProfit = Math.max(bestProfit, price - minPrice);
}
return bestProfit;
}
}Dry run
Take prices = [7, 1, 5, 3, 6, 4].
- start with
minPrice = 7,bestProfit = 0 - see
1: updateminPrice = 1 - see
5: profit is5 - 1 = 4, sobestProfit = 4 - see
3: profit is2, answer stays4 - see
6: profit is5, answer becomes5 - see
4: profit is3, answer stays5
Final answer: 5.
Common mistakes
1. Selling before buying
You can only compare the current day with prices that happened earlier.
2. Resetting the answer when a lower price appears
A lower price only changes the future buying option. It does not erase earlier profits you already found.
3. Confusing this with the multiple-transactions version
This problem allows only one buy and one sell.
Complexity
Time Complexity: O(n)
Space Complexity: O(1)