Javascript O(1) space O(n) time


  • 0
    var maximumProduct = function(nums) {
       var obj = nums.reduce((prev, num)=> {
           if (prev.min1 > num) {
                prev.min2 = prev.min1;
                prev.min1 = num;
           } else if (prev.min2 > num) {
                prev.min2 = num;
           }
           
           if (prev.max1 < num) {
                prev.max3 = prev.max2;
                prev.max2 = prev.max1;
                prev.max1 = num;
           } else if (prev.max2 < num) {
                prev.max3 = prev.max2;
                prev.max2 = num;
           } else if (prev.max3 < num) {
               prev.max3 = num;
           }
           return prev;
       }, {
           min1: Number.MAX_SAFE_INTEGER, 
           min2: Number.MAX_SAFE_INTEGER,
           max1: Number.MIN_SAFE_INTEGER,
           max2: Number.MIN_SAFE_INTEGER,
           max3: Number.MIN_SAFE_INTEGER
       });
        
        return Math.max(obj.min1*obj.min2*obj.max1,  obj.max3*obj.max2*obj.max1);
    };

Log in to reply
 

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