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
.
Array Dynamic Programming
0,a,b,c,d,e,f,g,h,0
1 #include <iostream> 2 using namespace std; 3 4 class Solution { 5 public: 6 int maxProduct(int A[], int n) { 7 if(n<2) return A[0]; 8 int retMax=A[0]; 9 int curval=1; 10 for(int i=0;i<n;i++){ 11 if(A[i]==0){ 12 if(0>retMax) retMax=0; 13 curval=1; 14 continue; 15 } 16 curval*=A[i]; 17 if(curval>retMax) retMax=curval; 18 } 19 curval = 1; 20 for(int i=n-1;i>=0;i--){ 21 if(A[i]==0){ 22 curval = 1; 23 continue; 24 } 25 curval*= A[i]; 26 if(curval>retMax) retMax= curval; 27 } 28 return retMax; 29 } 30 }; 31 32 int main() 33 { 34 int a[]={-1,0,-2}; 35 Solution sol; 36 cout<<sol.maxProduct(a,sizeof(a)/sizeof(int))<<endl; 37 return 0; 38 }
官方解法中结合了求最小值的解答,是一个标准的dp 过程,
[LeetCode] Maximum Product Subarray 连续数列最大积
原文:http://www.cnblogs.com/Azhu/p/4148248.html