You are given an array prices where prices[i] 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.
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Explanation: In this case, no transactions are done and the max profit = 0.
Using a brute force approach, we can try all possible combinations of buying and selling days and compute the profit for each combination. The maximum of these profits will be our answer.
Instead of trying all possible pairs of buy and sell days, we can iterate through the list of prices once while keeping track of the minimum price encountered so far. At each step, we calculate what the profit would be if we sold at the current price, and update the maximum profit correspondingly.
Scan prices left to right while maintaining:
At each day’s price p:
minPrice = min(minPrice, p). This locks in the cheapest buy seen so far.p - minPrice.maxProfit = max(maxProfit, p - minPrice).Return maxProfit after the scan.
(buyDay < sellDay). When you stand on sellDay = i, the best buy day is simply the cheapest price among days 0..i. That’s exactly minPrice after scanning up to i.i is prices[i] - minPrice. By checking this at every i, we consider the best “sell-today” profit for every possible sell day.maxProfit.