Beats 99.7%✅ | O( n )✅ | Python (Step by step explanation)
Intuition\nThe problem requires finding the maximum profit that can be obtained by buying and selling a stock. The key idea here is to track the minimum price e
# Intuition\nThe problem requires finding the maximum profit that can be obtained by buying and selling a stock. The key idea here is to track the minimum price encountered so far and calculate the profit if we sell at the current price. We update the maximum profit whenever a higher profit is encountered.\n\n# Approach\n1. Initialize `min_price` to the first price and `max_profit` to 0.\n2. Check if the `prices` list is empty. If it is, return 0 as there are no transactions to make.\n3. Iterate through the list of prices.\n4. For each price, compare it with `min_price`.\n   - If the current price is lower than `min_price`, update `min_price` to the current price.\n   - If the current price is higher than or equal to `min_price`, calculate the profit obtained by selling at the current price (`price - min_price`) and update `max_profit` if this profit is higher than the current `max_profit`.\n5. After iterating through all prices, `max_profit` will hold the maximum profit that can be obtained.\n\n# Complexity\n- Time complexity: O(n), where n is the number of prices\n- Space complexity: O(1), as we are using only a constant amount of extra space\n\n\n# Code\n```\nclass Solution:\n    def maxProfit(self, prices: List[int]) -> int:\n        if not prices:\n            return 0\n            \n        min_price = prices[0]\n        max_profit = 0\n        for price in prices:\n            if price < min_price :\n                min_price = price\n            else:\n                max_profit = max(max_profit , (price - min_price)) \n\n        return max_profit           \n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/be1a30af-8321-47bd-8c3e-2af71751f115_1697529633.6505737.jpeg)\n
['Sliding Window', 'Python3']