Best Time to Buy and Sell Stock
Difficulty: Easy
prices[i] is a stock's price on day i. You can buy on one day and sell on a later day.
Find the maximum profit. If no trade makes a profit, return 0 (you can choose not to trade).
Examples
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5
Buy on day 1 (price 1) and sell on day 4 (price 6). Profit = 6 - 1 = 5.
Input: prices = [7, 6, 4, 3, 1]
Output: 0
Prices only ever go down, so no trade makes a profit — best to not trade at all.
Input: prices = [2, 4, 1]
Output: 2
Buy on day 0 (price 2) and sell on day 1 (price 4). Profit = 2. Buying on day 2 is too late to sell for a profit.
Constraints
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^4
Approach
Brute force tries every buy day with every later sell day and keeps the best profit. That repeats a lot of work.
A faster way scans once, tracking the lowest price so far and the best profit so far. Each day, check the profit if you sold today after buying at the lowest price, and keep it if it's better. Then update the lowest price if today is lower.
One pass covers every valid buy-then-sell pair without looking back.
Solutions
Brute Force — Every Buy/Sell Pair
Try every buy day with every later sell day, tracking the best profit. Correct, but it checks the same days over and over.
function maxProfit(prices) {
let best = 0;
for (let buy = 0; buy < prices.length; buy++) {
for (let sell = buy + 1; sell < prices.length; sell++) {
const profit = prices[sell] - prices[buy];
if (profit > best) {
best = profit;
}
}
}
return best;
}Time: O(n²) · Space: O(1)
Optimal — Track the Running Minimum
Walk the prices once. Keep the lowest price so far as the buy point, and each day check the profit from selling today, updating the best answer.
function maxProfit(prices) {
let minPrice = Infinity;
let best = 0;
for (const price of prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > best) {
best = price - minPrice;
}
}
return best;
}Time: O(n) · Space: O(1)