[LC] 152. Maximum Product Subarray

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 152. Maximum Product Subarray相关的知识,希望对你有一定的参考价值。

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

class Solution {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int max = nums[0];
        int min = nums[0];
        int res = nums[0];
        int preMax = max;
        for (int i = 1; i < nums.length; i++) {
            // include the current for comparison
            max = Math.max(nums[i], Math.max(preMax * nums[i], min * nums[i]));
            min = Math.min(nums[i], Math.min(min * nums[i], preMax * nums[i]));
            res = Math.max(max, res);
            preMax = max;
        }
        return res;
    }
}

以上是关于[LC] 152. Maximum Product Subarray的主要内容,如果未能解决你的问题,请参考以下文章

152. Maximum Product Subarray

152. Maximum Product Subarray(js)

152. Maximum Product Subarray

leetcode 152. Maximum Product Subarray

刷题152. Maximum Product Subarray

LeetCode 152. Maximum Product Subarray