LeetCode Maximum Product SubArray

题目描述:https://oj.leetcode.com/problems/maximum-product-subarray/

题目大意:给定一个数组,求出其最大子段积,例如: [2,3,-2,4],最大子段积为6

思路:和最大子段和思路类似,DP可解。但是,要注意一点:除了要维护以a[i]为结尾的最大子段积max[i],还要维护以a[i]结尾的最小子段积min[i],为何?因为若a[i]为负数,通过min[i-1]和a[i]可以得到max[i]。


package Maximum_Product_Subarray;

public class Solution {
   public int maxProduct(int[] a) {
	 assert a.length > 0 ;
	 if(a.length == 1)
		 return a[0];
	  int[] max = new int[a.length];
	  int[] min = new int[a.length];
	  max[0] = a[0];
	  min[0] = a[0];
	  int ans = max[0];
	  for(int i=1;i=0){
			  max[i] = (a[i]>=a[i]*max[i-1])? a[i]:a[i]*max[i-1];
			  min[i] = (a[i]<=a[i]*min[i-1])? a[i]:a[i]*min[i-1];
		  }
		  else if(a[i]<0){
			  max[i] = (a[i]>=a[i]*min[i-1])? a[i]:a[i]*min[i-1];
			  min[i] = (a[i]<=a[i]*max[i-1])? a[i]:a[i]*max[i-1];
		  }
		  if(max[i]>ans)
			 ans = max[i];
	  }
	   return ans;
   }
   
   public static void main(String[] args){
  	   int[] test = new int[]{-2,-4,0};
    System.out.println(new Solution().maxProduct(test));
   }
}


你可能感兴趣的:(算法_动态规划,LeetCode)