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/

转载于:https://www.cnblogs.com/forcheryl/p/3992327.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值