Find the buy and sell days that maximize stock profit
A trading dashboard replays a stock’s daily closing prices and highlights the single best trade a user could have made: buy on one day, sell on a later day. Implement bestTradeWindow(prices), which returns the days to highlight and the profit.
bestTradeWindow(prices) // => { buy, sell, profit } | null
prices[i] is the closing price on day i. buy and sell are day indexes, and profit is prices[sell] - prices[buy].
buy must be strictly less than sell.0. If no trade makes money (prices never rise, or there are fewer than two days), return null.prices. Prices are non-negative integers.bestTradeWindow([7, 2, 5, 1, 6, 4]);
// => { buy: 3, sell: 4, profit: 5 } (buy at 1, sell at 6)
bestTradeWindow([3, 8, 1, 6]);
// => { buy: 0, sell: 1, profit: 5 } (1 -> 6 also earns 5, but sells later)
bestTradeWindow([2, 5, 2, 7]);
// => { buy: 0, sell: 3, profit: 5 } (day 0 and day 2 both cost 2; day 0 is earlier)
bestTradeWindow([9, 7, 4, 4, 1]);
// => null (the price never rises)
bestTradeWindow([5]);
// => null