Most optimized solution, easy to understand || C++ || JAVA || Python
Approach\nTo solve this problem, I employed a straightforward approach that iterates through the array of stock prices. At each step, I kept track of the minimu
# Approach\nTo solve this problem, I employed a straightforward approach that iterates through the array of stock prices. At each step, I kept track of the minimum stock price seen so far (`min_price`) and calculated the potential profit that could be obtained by selling at the current price (`prices[i] - min_price`). I updated the `maxprof` (maximum profit) variable with the maximum of its current value and the calculated profit. Additionally, I updated the `min_price` to be the minimum of the current stock price and the previously seen minimum.\n\n# Complexity\n- Time complexity: $$O(n)$$\nThe algorithm iterates through the array of stock prices once, performing constant-time operations at each step. Therefore, the time complexity is linear in the size of the input array.\n\n- Space complexity: $$O(1)$$\nThe algorithm uses a constant amount of extra space to store variables like `min_price` and `maxprof`. The space complexity remains constant regardless of the size of the input array.\n\n\n# Code\n``` cpp []\nclass Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        int min_price = prices[0];\n        int maxprof = 0;\n\n        for(int i=1;i<prices.size();i++){\n            maxprof = max(maxprof,prices[i]-min_price);\n            min_price = min(prices[i],min_price);\n        }\n\n        return maxprof;\n    }\n};\n```\n\n``` java []\nclass Solution {\n    public int maxProfit(int[] prices) {\n        int min_price = prices[0];\n        int maxprof = 0;\n\n        for(int i=1;i<prices.length;i++){\n            maxprof = Math.max(maxprof,prices[i]-min_price);\n            min_price = Math.min(prices[i],min_price);\n        }\n\n        return maxprof;\n    }\n}\n```\n\n``` python3 []\nclass Solution:\n    def maxProfit(self, prices: List[int]) -> int:\n        min_price = prices[0]\n        max_profit = 0\n        \n        for price in prices[1:]:\n            max_profit = max(max_profit, price - min_price)\n            min_price = min(min_price, price)\n            \n        return max_profit\n```\n\nHope you liked the Solution,\nIf you have any questions or suggestions, feel free to share \u2013 happy coding!\n\n---\n\n\n![pleaseupvote.jpg](https://assets.leetcode.com/users/images/a79b8806-f22f-40aa-91d5-be9118ab659f_1692112738.478644.jpeg)\n
['Array', 'Dynamic Programming', 'Python', 'C++', 'Java', 'Python3']