(leedcode)152. Maximum Product Subarray

//讨论区看到别人的解法,思路就是左到右,右到左扫描两遍,取最大的
//其中碰到0的时候,当作是分界符,重新计算这个值
public int maxProduct(int[] nums) {
    int max = Integer.MIN_VALUE, product = 1;
    int len = nums.length;

    for(int i = 0; i < len; i++) {
        max = Math.max(product *= nums[i], max);
        if (nums[i] == 0) product = 1;
    }

    product = 1;
    for(int i = len - 1; i >= 0; i--) {
        max = Math.max(product *= nums[i], max);
        if (nums[i] == 0) product = 1;
    }

    return max;
}
点赞