Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.
X

LeetCode: Maximum Product Subarray (1ms)


public class Solution {
    public int maxProduct(int[] nums) {
        
        int max = 1;
        int leftToRightMax = nums[0];
        int rightToLeftMax = nums[0];

        //Transverse from left to right keeping the max
        for (int j = 0; j < nums.length ; j++) {
             max = max * nums[j];

             if (max > leftToRightMax) {
                 leftToRightMax = max;
             }
             
             if (max == 0) {
                 max = 1;
             }
        }

        max = 1;

        //Transverse from right to left keeping the max
        for (int j = nums.length - 1; j >= 0 ; j--) {
            max = max * nums[j];

            if (max > rightToLeftMax) {
                rightToLeftMax = max;
            }
            
             if (max == 0) {
                 max = 1;
             }
        }

        max = Math.max(leftToRightMax, rightToLeftMax);

        return max;
    }
}

 


comments powered by Disqus