You are given an array prices where prices[i] is the price of a given stock on the i-th 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.* Input: An array of integers prices.* Output: An integer representing the maximum profit.* Constraints:* 1 <= prices.length <= 10^5* 0 <= prices[i] <= 10^4* Example:Input: prices = [7,1,5,3,6,4]Output: 5Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.Not 7-1 = 6, as selling price needs to be after buying price.
Solution
- Approach: We can iterate through the
pricesarray, keeping track of the minimum price seen so far and the maximum profit found.* Initializemin_priceto a very large number (e.g., infinity orprices[0]).* Initializemax_profitto0.* For eachpricein thepricesarray:* Updatemin_price = min(min_price, price)to find the lowest buy price up to the current day.* Updatemax_profit = max(max_profit, price - min_price)to find the maximum profit that could be made by selling at the current price with the lowest buy price seen so far.* Returnmax_profitafter iterating through all prices.* Complexity:* Time: O(N) because we iterate through the array once.* Space: O(1) as we only use a few variables.pythonclass Solution: def maxProfit(self, prices: list[int]) -> int: min_price = float('inf') max_profit = 0 for price in prices: min_price = min(min_price, price) max_profit = max(max_profit, price - min_price) return max_profit
