Best Time to Buy and Sell Stock
You are given an array prices where pricesi is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. Track the minimum price seen so far in one pass, and compare each day against that running minimum to find the best profit.
Constraints
- 1 ≤ prices.length ≤ 105
- 0 ≤ pricesi ≤ 104
Example
prices = [7, 1, 5, 3, 6, 4]5Explanation Buy on day 1 (price = 1) and sell on day 4 (price = 6), profit = 6 - 1 = 5.
Track the running minimum price
Day 0: price 7 — set as running minimum. Best profit = 0.
What happens in this step
minPrice = prices[0] = 7 bestProfit = 0 No later day has been compared yet, so profit starts at 0.
Steps to visualize
- Start with the running minimum at the first day's price and best profit at 0.
- Move right one day at a time.
- If today's price is lower than the running minimum, update the minimum.
- Otherwise compute profit as price minus the running minimum and update best if it improves.
- Stop after scanning the last day.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Day 0: price 7 — set as running minimum. Best profit = 0.
What happens in this step
minPrice = prices[0] = 7 bestProfit = 0 No later day has been compared yet, so profit starts at 0.
Solution
function maxProfit(prices) {
if (prices.length === 0) {
throw new Error("prices must contain at least one price");
}
let minPrice = prices[0];
let bestProfit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else {
bestProfit = Math.max(bestProfit, prices[i] - minPrice);
}
}
return bestProfit;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
prices = [7, 1, 5, 3, 6, 4] | 5 | example from the docstring |
prices = [5] | 0 | smallest valid input: single day, no transaction possible |
prices = [3, 3, 3, 3] | 0 | all identical prices |
prices = [9, 7, 5, 3, 1] | 0 | prices only decrease, so no profit is possible |
prices = [1, 2, 3, 4, 5] | 4 | prices only increase: best is buy first, sell last |
prices = [0, 0, 0, 0] | 0 | boundary value: prices can be 0 |
prices = [3, 2, 6, 5, 0, 3, 9, 4] | 9 | larger, hand-verified case |