C++/Java/Python/JavaScript || ✅🚀Simple Code || ✔️🔥Easy To Understand
Intuition:\nThe intuition behind this solution is to find the maximum profit by keeping track of the minimum price encountered so far. By iterating over the pri
# Intuition:\nThe intuition behind this solution is to find the maximum profit by keeping track of the minimum price encountered so far. By iterating over the prices, we update the minimum price if we find a smaller price. Then, we calculate the profit by subtracting the minimum price from the current price, and update the maximum profit if it is larger.\n\n# Approach:\n1. Initialize the variables `profit` and `minPrice` to 0 and INT_MAX respectively.\n2. Iterate over the `prices` vector using a for loop, with index `i` ranging from 0 to `prices.size() - 1`.\n3. Inside the loop, update the `minPrice` by taking the minimum of the current `minPrice` and the price at index `i`.\n4. Calculate the profit by subtracting the `minPrice` from the price at index `i`.\n5. Update the `profit` by taking the maximum of the current `profit` and the calculated profit.\n6. After the loop ends, return the `profit`.\n\n# Complexity:\n- The time complexity of this solution is O(n), where n is the size of the `prices` vector, as we iterate over the vector once.\n- The space complexity is O(1) as we only use a constant amount of additional space to store the variables `profit` and `minPrice`.\n\n---\n# C++\n```\nclass Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        int profit=0;\n        int minPrice=INT_MAX;\n        for(int i=0;i<prices.size();i++){\n            minPrice = min(minPrice,prices[i]);\n            profit = max(profit,prices[i]-minPrice);\n        }\n        return profit;\n    }\n};\n```\n\n---\n# Java\n```\nclass Solution {\n    public int maxProfit(int[] prices) {\n        int profit = 0;\n        int minPrice = Integer.MAX_VALUE;\n        for (int i = 0; i < prices.length; i++) {\n            minPrice = Math.min(minPrice, prices[i]);\n            profit = Math.max(profit, prices[i] - minPrice);\n        }\n        return profit;\n    }\n}\n\n```\n---\n# Python\n```\nclass Solution(object):\n    def maxProfit(self, prices):\n        profit = 0\n        minPrice = float("inf")\n        for price in prices:\n            minPrice = min(minPrice, price)\n            profit = max(profit, price - minPrice)\n        return profit\n\n```\n---\n# JavaScript\n```\nvar maxProfit = function(prices) {\n    let profit = 0;\n    let minPrice = Number.MAX_VALUE;\n    for (let i = 0; i < prices.length; i++) {\n        minPrice = Math.min(minPrice, prices[i]);\n        profit = Math.max(profit, prices[i] - minPrice);\n    }\n    return profit;  \n};\n```
['Array', 'Python', 'C++', 'Java', 'JavaScript']