leetcode-Maximum Product Subarray-ZZ

http://blog.csdn.net/v_july_v/article/details/8701148

假设数组为a[],直接利用动归来求解,考虑到可能存在负数的情况,我们用Max来表示以a结尾的最大连续子串的乘积值,用Min表示以a结尾的最小的子串的乘积值,那么状态转移方程为:

       Max=max{a[i], Max[i-1]*a[i], Min[i-1]*a[i]};
       Min=min{a[i], Max[i-1]*a[i], Min[i-1]*a[i]};
    初始状态为Max[0]=Min[0]=a[0]。

 1 #include <iostream>
 2 #include <cmath>
 3 #include <algorithm>
 4 using namespace std;
 5 class Solution {
 6 public:
 7     int maxProduct(int A[], int n) {
 8         int *maxArray = new int[n];
 9         int *minArray = new int[n];
10         maxArray[0] = minArray[0] = A[0];
11         int result=maxArray[0];
12         for (int i = 1; i < n; i++)
13         {
14             maxArray[i] = max(max(maxArray[i-1]*A[i],minArray[i-1]*A[i]),A[i]);
15             minArray[i] = min(min(maxArray[i-1]*A[i],minArray[i-1]*A[i]),A[i]);
16             result = max(result,maxArray[i]);
17         }
18         return result;
19     }
20 };
21 int main()
22 {
23     Solution s;
24     int n = 4;
25     int a[] = {2,3,-2,4};
26     cout << s.maxProduct(a,4)<<endl;
27     return 0;
28 }

 

==============================================================================================

LinkedIn - Maximum Sum/Product Subarray 

Maximum Sum Subarray是leetcode原题,跟Gas Station的想法几乎一模一样。解答中用到的结论需要用数学简单地证明一下。

1
2
3
4
5
6
7
8
9
10
11
12
public int maxSubArray(int[] A) {
    int sum = 0;
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < A.length; i++) {
        sum += A[i];
        if (sum > max)
            max = sum;
        if (sum < 0)
            sum = 0;
    }
    return max;
}

Maximum Product Subarray其实只需要不断地记录两个值,max和min。max是到当前为止最大的正product,min是到当前为止最小的负product,或者1。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public int maxProduct(int[] A) {
    int x = 1;
    int max = 1;
    int min = 1;
    for (int i = 0; i < A.length; i++) {
        if (A[i] == 0) {
            max = 1;
            min = 1;
        } else if (A[i] > 0) {
            max = max * A[i];
            min = Math.min(min * A[i], 1);
        } else {
            int temp = max;
            max = Math.max(min * A[i], 1);
            min = temp * A[i];
        }
        if (max > x)
            x = max;
    }
    return x;
}

 

http://shepherdyuan.wordpress.com/2014/07/23/linkedin-maximum-sumproduct-subarray/

posted @ 2014-09-25 11:06  Ryan in C++  阅读(318)  评论(0编辑  收藏  举报