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.

 

Show Company Tags
Show Tags
Show Similar Problems
 
思路:这种maximum subarray的问题都很类似,比较到这个数之前到和/乘积和现在这个数点的大小。只是这个会出现负数的情况,
所以用一个负数的dp来记录最小值,正数的dp来比较现在这个数,之前的乘积和现在这个数以及负数乘以现在这个数的大小。存max。
public class Solution {
    public int maxProduct(int[] nums) {
        int[] pos=new int[nums.length];
        int[] neg=new int[nums.length];
        pos[0]=nums[0];
        neg[0]=nums[0];
        int max=nums[0];
        for(int i=1;i<nums.length;i++)
        {
            pos[i]=Math.max(Math.max(neg[i-1]*nums[i],pos[i-1]*nums[i]),nums[i]);
            neg[i]=Math.min(Math.min(neg[i-1]*nums[i],pos[i-1]*nums[i]),nums[i]);
            max=Math.max(pos[i],max);
        }
        return max;
    }
}

 

posted on 2016-09-22 04:47  Machelsky  阅读(135)  评论(0)    收藏  举报