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.

这道题需要用动态规划方法解决(自底向上),首先动态规划有两个特点,一个是最优子结构,另一个是重叠子问题。我们先求出子问题的最小乘积(可能会是负数)和最大乘积,然后与当前的数组值相乘和当前的值进行比较(maxhere和minhere),同样保存最大值和最小值。代码如下:

public class Solution {

    public int maxProduct(int[] nums) {

        int maxherepre = nums[0];

        int minherepre = nums[0];

        int maxsofar = nums[0];

        int maxhere=nums[0],minhere=nums[0];

        for(int i=1;i<nums.length;i++){

            maxhere = Math.max(nums[i],Math.max(maxherepre*nums[i],minherepre*nums[i]));

            minhere = Math.min(nums[i],Math.min(maxherepre*nums[i],minherepre*nums[i]));

            maxsofar = Math.max(maxsofar,maxhere);

            maxherepre = maxhere;

            minherepre = minhere;

        }

        return maxsofar;

    }

}

原文地址:https://www.cnblogs.com/codeskiller/p/6357424.html