Best Time to Buy and Sell Stock
Difficulty: Easy · Pattern: Sliding Window · LeetCode #121
prices[i] is a stock's price on day i. You may buy on one day and sell on a later day, once. Return the maximum profit possible, or 0 if no profitable trade exists.
Examples
text
prices = [8, 3, 6, 2, 9, 4] → 7 (buy at 2, sell at 9)
prices = [9, 7, 4, 1] → 0Hints
- For each selling day, the best buying day is the cheapest day before it.
- Keep a running minimum as you scan.
Approach
Scan left to right, maintaining lo, the lowest price seen so far (the window's left edge is always the best buy). On each day, price − lo is the best profit for selling today; track the maximum. If today's price is a new low, it becomes the new buy point.
Complexity
Time: O(n). Space: O(1).
Python solution
def maxProfit(prices):
lo, best = float('inf'), 0
for p in prices:
lo = min(lo, p)
best = max(best, p - lo)
return bestJavaScript solution
function maxProfit(prices) {
let lo = Infinity, best = 0;
for (const p of prices) {
lo = Math.min(lo, p);
best = Math.max(best, p - lo);
}
return best;
}