Maximum Product Subarray

题目地址:
https://leetcode.com/problems/maximum-product-subarray/#/description

题目:
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.

解题思路:
用三个temp的变量max,min,rst来存储,每次更新。

代码:

public int maxProduct(int[] nums) {
    if(nums == null || nums.length == 0){
        return 0;
    }
    int max = nums[0], min = nums[0], rst = nums[0];
    for(int i = 1; i <= nums.length - 1; i++){
        int temp = max;
        max = Math.max(nums[i], Math.max(nums[i] * temp, nums[i] * min));
        min = Math.min(nums[i], Math.min(nums[i] * temp, nums[i] * min));
        if(max > rst){
            rst = max;
        }
    }
    return rst;
}

Comments

Popular Posts