Best Time to Buy and Sell Stock
This is the single-transaction version of the stock profit problem. You can buy once and sell once, so every day asks one question: "If I sell today, what was the best earlier price to buy at?"
Problem
Given an array prices, where prices[i] is the stock price on day i, return the maximum profit from one buy and one sell.
Rules:
- buy before you sell
- at most one transaction
- return
0if no profitable trade exists
First Attempt
public int maxProfit(int[] prices) {
var n = prices.length;
var minPrice = prices[0];
var maxProfit = 0;
for (int i = 1; i < n; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
}
var cp = prices[i] - minPrice;
if (cp > maxProfit) {
maxProfit = cp;
}
}
return maxProfit;
}
This is already the right algorithm. It tracks:
minPrice: the lowest price seen so farmaxProfit: the best profit found so far
The variable cp means current profit: selling today after buying at the best earlier price.
Clean Version
class Solution {
public int maxProfit(int[] prices) {
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
minPrice = Math.min(minPrice, prices[i]);
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
}
return maxProfit;
}
}
Walkthrough
Input:
prices = [7, 1, 5, 3, 6, 4]
Steps:
| day | price | min so far | profit if sold today | max profit |
|---|---|---|---|---|
| 0 | 7 | 7 | 0 | 0 |
| 1 | 1 | 1 | 0 | 0 |
| 2 | 5 | 1 | 4 | 4 |
| 3 | 3 | 1 | 2 | 4 |
| 4 | 6 | 1 | 5 | 5 |
| 5 | 4 | 1 | 3 | 5 |
Best trade:
buy at 1
sell at 6
profit = 5
Why This Works
At each day, we only need the cheapest price before or at that day.
If today's price is lower than minPrice, it becomes the new best buy candidate.
If today's price is higher, selling today gives:
prices[i] - minPrice
We keep the maximum of those candidate profits.
Stock I vs Stock II
| Problem | Transactions | Pattern |
|---|---|---|
| Best Time to Buy and Sell Stock | One buy and one sell | Track minimum so far |
| Best Time to Buy and Sell Stock II | Unlimited transactions | Sum every positive daily gain |
The first problem needs one best global trade.
The second problem collects every profitable rise.
Edge Cases
[7, 6, 4, 3, 1] -> 0
[7, 1, 5, 3, 6, 4] -> 5
[1, 2] -> 1
[2, 1] -> 0
For the usual LeetCode constraints, prices.length >= 1. If that is not guaranteed, add:
if (prices == null || prices.length == 0) {
return 0;
}
Complexity
| Approach | Time | Space |
|---|---|---|
| Track minimum so far | O(n) | O(1) |
Takeaways
- For one transaction, track the cheapest price seen so far.
- Compute current profit as
prices[i] - minPrice. - Keep the best profit across all sell days.
- Do not sum all rises here; that belongs to Stock II.