Chinaunix首页 | 论坛 | 博客
  • 博客访问: 117354
  • 博文数量: 53
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-24 16:22
文章存档

2014年(53)

我的朋友

分类: C/C++

2014-10-07 14:07:10

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.


求一串数字的最大子串积。这不禁让人想到了最大子串和的那个问题,不过这个问题和那个不一样,子串和是这么做的:

从头到尾尝试着累加子串字符和为sum,一旦sum<0,则sum=0,然后继续累加,在这个过程中一直更新最大值。

我开始做这道题用的是DP,本质上就是遍历,但因为是DP,报了Memory Limit Exceeded错误。

  1. int maxProduct(int A[], int n) {
  2.     vector<vector<int>> dp(n,vector<int>(n,0));
  3.     int max=A[0];
  4.     for(int i=0;i<n;i++){
  5.         dp[i][i]=A[i];
  6.         if(dp[i][i]>max)
  7.             max=dp[i][i];
  8.     }
  9.     for(int i=0;i<n-1;i++){
  10.         for(int j=i+1;j<n;j++){
  11.             dp[i][j]=dp[i][j-1]*A[j];
  12.             if(dp[i][j]>max)
  13.             max=dp[i][j];
  14.         }
  15.     }
  16.     return max;
  17. }
后来只好放弃了遍历,采用另一种思路:
子串积要是有S[i]参与,则可能是:
1) i之前的最大的子串积*S[i]
2) i之前的最小的子串积*S[i]
3) S[i]

取它们的最大值,即为以S[i]为尾的最大子串积,把i从0到n-1遍历,得到最大子串积。

代码如下,注意这段代码稍作改动可求最小子串积。

  1. int maxProduct(int A[], int n) {
  2.     if(n==0)
  3.         return 0;
  4.     else if(n==1)
  5.         return A[0];
  6.     else{
  7.         int curmax=A[0];
  8.         int curmin=A[0];
  9.         int result=A[0];
  10.         for(int i=1;i<n;i++){
  11.             int a=curmax*A[i];
  12.             int b=curmin*A[i];
  13.             curmax=max(A[i],max(a,b));
  14.             curmin=min(A[i],min(a,b));
  15.             result=max(result,curmax);
  16.         }
  17.         return result;
  18.     }
  19. }
阅读(982) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~