Best time to buy and sell stock
Easy TimeO(n) SpaceO(1)
prices[i] is a stock's price on day i. Exactly one buy and one sell are allowed, the sale on a later day — selling on the day of the purchase earns nothing. Return the greatest profit available, or 0 when no trade makes money, which is what prices that only ever fall give.
Examples
Example 1
- Input
- prices = [7, 1, 5, 3, 6, 4]
- Output
- Buy at
51on day 1 and sell at6on day 4:6 − 1= 5.
Example 2
- Input
- prices = [7, 6, 4, 3, 1]
- Output
- Every day is cheaper than the last, so no sale beats its purchase and no trade is made.
0
The Code
function maxProfit(prices) {
let cheapest = prices[0];
let best = 0;
for (let i = 1; i < prices.length; i++) {
const profit = prices[i] - cheapest;
if (profit > best) best = profit;
if (prices[i] < cheapest) cheapest = prices[i];
}
return best;
}
maxProfit([7, 1, 5, 3, 6, 4]);Done