UVa11059 Maximum Product

题目:输入n个元素组成的序列s,你需要找出一个乘积最大的连续子序列,如果这个最大的乘积不是正数,输出0,表示无解。

1<=n<=18, -10<=Si<=10

样例输入:

3

2 4 -3

2 5 -1 2 -1

样例输出:

8

20

 

最简单的暴力枚举:

#include <iostream>
#include <algorithm>
using namespace std;
#define MaxSize 20
int main(){
    int n;
    cin>>n;
    int line[MaxSize];
    long long int max_=-10000000;
    for(int i=0; i<n; ++i)  cin>>line[i];
    //最常见的枚举法
    for(int i=1; i<=n; ++i)  //连续序列的长度为i
        for(int j=0; j<=n-i; ++j){ //连续序列的起始位置j
            long long int temp=1;
            for(int z=j; z-j<i; ++z)  temp *= line[z]; //连续序列的临时位置z
            max_ = max(max_, temp);
        }
    
    printf("%lld", max_);
    return 0;
}

还有一种复杂一点的用动态规划来写:

//动态规划来写:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef long long LL;

const int maxn = 25;
LL dp_max[maxn],dp_min[maxn];
int iCase = 1;

int main()
{
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    int n;
    while(cin >> n){
        dp_max[0] = dp_min[0] = 0LL;
        LL Max = 0;
        int x;
        for(int i = 1;i <= n;i++){
            cin >> x;
            if(x > 0){
                dp_max[i] = dp_max[i-1]*x;
                dp_min[i] = dp_min[i-1]*x;
                if(!dp_max[i]) dp_max[i] = x;
            }
            else if(x < 0){
               dp_max[i] = dp_min[i-1]*x;
               dp_min[i] = dp_max[i-1]*x;
               if(!dp_min[i]) dp_min[i] = x;
            }
            else{
                dp_max[i] = dp_min[i] = 0LL;
            }
            if(Max < dp_max[i] && x) Max = dp_max[i];
        }
        printf("Case #%d: The maximum product is %lld.\n\n",iCase++,Max);
    }
    return 0;
}

 

posted @ 2020-04-18 20:31  Abel_chen  阅读(169)  评论(0)    收藏  举报