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.

題意:找數(shù)組中乘積最大的連續(xù)子數(shù)組。

思路:maxLocal和minLocal分別代表到當(dāng)前為止最大乘積和最小乘積,如果當(dāng)前數(shù)字時正數(shù),那么最大值在當(dāng)前數(shù)字和它乘以maxLocal之中產(chǎn)生,否則在它和minLocal乘積中產(chǎn)生。

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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。