Best Time to Buy and Sell Stock
Pattern: Stock buy and sell
One buy and one later sale. Walk the prices keeping the lowest price so far; selling today earns today's price minus it.
The problem
Given daily prices, choose one day to buy and a later day to sell. Return the largest profit, or 0 if no profit is possible.
Think first
- For a sale today, which buy day is best?
- What must you track as you go?
- What if prices only fall?
Hints
Brute force, and why it fails
Try every pair of days: O(n²).
The key insight
The best buy for each sale day is the minimum before it, which can be kept in one variable.
Dry run
| low | 1 |
|---|
[7, 1, 5, 3, 6, 4]. Lowest so far becomes 1 on day 1.
Step 1 of 2
The plan
low = inf; best = 0
for p: low = min(low, p); best = max(best, p - low)
Complexity
- Time
O(n)- Space
O(1)
One pass.
Edge cases
- One day: 0.
- Falling prices: 0.
- Equal prices: 0.
I've built my logic, show the code
Java
class Solution {
public int maxProfit(int[] prices) {
int lowest = Integer.MAX_VALUE, best = 0;
for (int p : prices) {
lowest = Math.min(lowest, p); // the cheapest day to have bought so far
best = Math.max(best, p - lowest); // selling today
}
return best;
}
}C++
class Solution {
public:
int maxProfit(vector<int>& prices) {
int lowest = INT_MAX, best = 0;
for (int p : prices) {
lowest = min(lowest, p); // the cheapest day to have bought so far
best = max(best, p - lowest); // selling today
}
return best;
}
};Python
class Solution:
def maxProfit(self, prices: list[int]) -> int:
lowest, best = float("inf"), 0
for p in prices:
lowest = min(lowest, p) # the cheapest day to have bought so far
best = max(best, p - lowest) # selling today
return bestCommon mistakes
- Selling before buying.
- Returning a negative profit.