☕ Java - 2ms - Sliding Window - Explanation - Simple - O(N)
The key to solving this problem is realizing that once a local minima is found, it is never more profitable going forward to buy on a day that costs more money.
The key to solving this problem is realizing that once a local minima is found, it is never more profitable going forward to buy on a day that costs more money. This is because we only have one day to choose to buy and one day to choose to sell.\n\nIf you are having trouble understanding why this solution works, then I would recommend simulating on paper what the code would do for two or more test cases.\n\n**Runtime Complexity - O(N)**\n**Memory Complexity - O(1)**\nwhere N is the size of the input array "prices".\n```\n    public int maxProfit(int[] prices) {\n        int maxProfit = 0;\n        \n        int minSeenSoFar = prices[0];\n        for(int day = 1; day < prices.length; day++) {\n            int priceToday = prices[day];\n            \n            if(priceToday < minSeenSoFar) {\n                minSeenSoFar = priceToday;\n                continue;\n            }\n            \n            maxProfit = Math.max(maxProfit, priceToday - minSeenSoFar);\n        }\n        \n        return maxProfit;\n    }\n```
['Sliding Window', 'Java']