Leetcode 152. Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

题意:找数组中乘积最大的连续子数组。

思路:maxLocal和minLocal分别代表到当前为止最大乘积和最小乘积,如果当前数字时正数,那么最大值在当前数字和它乘以maxLocal之中产生,否则在它和minLocal乘积中产生。

public int maxProduct(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }

    int max = nums[0];
    int maxLocal = nums[0];
    int minLocal = nums[0];

    for (int i = 1; i < nums.length; i++) {
        if (nums[i] < 0) {
            int tmp = maxLocal;
            maxLocal = minLocal;
            minLocal = tmp;
        }
        maxLocal = Math.max(nums[i], maxLocal * nums[i]);
        minLocal = Math.min(nums[i], minLocal * nums[i]);
        max = Math.max(max, maxLocal);
    }

    return max;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/87e9f3649e97
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞