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 prices array, keeping track of the minimum price seen so far and the maximum profit found.* Initialize min_price to a very large number (e.g., infinity or prices[0]).* Initialize max_profit to 0.* For each price in the prices array:* Update min_price = min(min_price, price) to find the lowest buy price up to the current day.* Update max_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.* Return max_profit after 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