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

Solution: 记录min, max. 每次
max = Math.max(max * nums[i], min * nums[i], nums[i]);
min = Math.min(max * nums[i], min * nums[i], nums[i]);

累乘的最大值(正数)碰到了一个正数;累乘的最小值(负数)碰到了一个负数;新的起点

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

results matching ""

    No results matching ""