O(1) extra space simple Java solution, No Kadane's Algorithm


  • 0
    M
    class Solution {
        public int maxProfit(int[] prices) {
            if (prices == null || prices.length == 0) return 0;
            int maxProfit = Integer.MIN_VALUE, minPrice = Integer.MAX_VALUE;
            
            for (int i = 0; i < prices.length; i++) {
                if (prices[i] < minPrice) minPrice = prices[i];
                maxProfit = Math.max(maxProfit, prices[i] - minPrice);
            }
            return maxProfit;
        }
    }
    

    the codes state itself clearly, no explanation needed.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.