13 lines concise Java code O(1) extra space & O(n) time


  • 1
    L
    public class Solution {
        public int maxProduct(int[] nums) {
            if(nums == null || nums.length == 0) return 0;
            int res = Integer.MIN_VALUE, prevMax = 1, prevMin = 1;
            for(int num : nums)
            {
                int val1 = num * prevMax;
                int val2 = num * prevMin;
                prevMax = Math.max(num, Math.max(val1, val2));
                prevMin = Math.min(num, Math.min(val1, val2));
                res = Math.max(res, prevMax);
            }
            return res;
        }
    }
    

  • 0
    E

    @linnn_hit This is by far the best solution


Log in to reply
 

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