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.

题目解答

题目分析

记录当前最大, 最小值. 因为遇到负数时, 与最小值的product可能成为最大值

代码实现

public class Solution {
    public int maxProduct(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        if(nums.length < 2)
            return nums[0];
        int len = nums.length;
        int max = nums[0];
        int min = nums[0];
        int ret = nums[0];
        for(int i = 1; i < len; i++) {
            int a = max*nums[i];
            int b = min*nums[i];

            max = Math.max(Math.max(a,b), nums[i]);
            min = Math.min(Math.min(a,b), nums[i]);

            ret = Math.max(max, ret);
        }
        return ret;
    }
}

你可能感兴趣的:(Maximum Product Subarray)