Easy to understand Java solution, 20 lines of code O(n) time complexity, O(1) space complexity


  • 0
    P
        public int maxProduct(int[] nums) {
            if(nums.length == 0) {
                return 0;
             }
             int currProdMax = nums[0], currProdMin = nums[0], maxProd = nums[0], tempMax = 0;
             for(int i = 1 ; i < nums.length; i++) {
                 if(nums[i] == 0 || currProdMax == 0) {
                     currProdMax = nums[i];
                     currProdMin = nums[i];
                 } else {
                    tempMax = Math.max(Math.max(currProdMax * nums[i], nums[i]), currProdMin*nums[i]);
                    currProdMin = Math.min(Math.min(currProdMax * nums[i], nums[i]), currProdMin*nums[i]);
                    currProdMax = tempMax;
                 }
                 maxProd = Math.max(currProdMax, maxProd);
             }
             return maxProd;
        }
    }

Log in to reply
 

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