Skip to content

152. Maximum Product Subarray

Jacky Zhang edited this page Nov 6, 2016 · 2 revisions

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.

解题思路为Dynamic Programming。

令f(i)表示以nums[i]结尾的largest product subarray, g(i)表示以nums[i]结尾的smallest product subarray。

f(i) = max(nums[i], f(i-1)*nums[i], g(i-1)*nums[i])

g(i) = min(nums[i], f(i-1)*nums[i], g(i-1)*nums[i])

public class Solution {
    public int maxProduct(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int max = nums[0], min = nums[0], res = nums[0];
        for(int i = 1; i < nums.length; i++) {
            int preMax = max, preMin = min;
            max = Math.max(Math.max(nums[i], preMax * nums[i]), preMin * nums[i]);
            min = Math.min(Math.min(nums[i], preMax * nums[i]), preMin * nums[i]);
            res = Math.max(res, max);
        }
        return res;
    }
}
Clone this wiki locally