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.

第一印象是DP,不过用了个比较啰嗦的解法

题目中是整数类型,就比较简单了,把数组按0分开,子数组的最大乘积肯定就是最大乘积了

 1 class Solution {
 2 public:
 3     int product(vector<int> & arr,int s,int e){
 4         int sum = INT_MIN;
 5         if(s<e) {
 6             sum = 1;
 7             for(int i = s;i<e;++i){
 8                 sum *= arr[i];
 9             }
10         }
11         return sum;
12     }
13 
14     int calcMax( vector<int> & arr,int s,int e) {
15         vector<int> v(e-s);
16         int sum = INT_MIN;
17         copy(arr.begin()+s,arr.begin()+e,v.begin());
18         int negativCount = count_if(v.begin(),v.end(),[](int x){return x<0;});
19         if(negativCount%2==0){
20             //有偶数个负数直接得乘积
21             sum = product(v,0,v.size());
22         }else{
23             //奇数个负数分别算下两边的最大值
24             int l =  find_if(v.begin(),v.end(),[](int x){return x<0;}) - v.begin();
25             int lmax = max(product(v,0,l),product(v,l+1,v.size()));
26             int r = find_if(v.rbegin(),v.rend(),[](int x){return x<0;}).base() - v.begin()-1;
27             int rmax = max(product(v,0,r),product(v,r+1,v.size()));
28             sum = max(lmax,rmax);
29         }
30         return sum;
31     }
32 
33     int maxProduct(int A[], int n) {
34         vector<int> arr(A,A+n);
35         vector<int> val;
36         //将数组按0分割成子数组,分别计算每个子数组的最大乘积
37         int s = -1 , e = 0;
38         while(true) {
39             if(arr[e]==0 || e==arr.size()) {
40                 if(s+1 != e)
41                     val.push_back(calcMax(arr,s+1,e));
42                 s = e;
43             }
44             ++e;
45             if(e>arr.size())break;
46         }
47         //防止数组只有一个元素的情况
48         val.push_back(*max_element(arr.begin(),arr.end()));
49         return *max_element(val.begin(),val.end());
50     }
51 };

 



 

posted @ 2014-10-22 11:21  Madao_  阅读(138)  评论(0)    收藏  举报