7-2 Maximum Product

The second question of the violence series

The problem is to input a sequence of n elements, and find the maximum product that can be formed by consecutive subsequences.

It is worth mentioning that the data range of this question is very small, n<=18, and the absolute value of each number in the sequence does not exceed 10, so violence is completely feasible.

The general idea is to enumerate every possible product and use greedy replacement to find the maximum.

Note that longlong must be opened, and int cannot fit 10^18.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[20],n;
long long b[20],maxx;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        b[i]++;
    }
    long long x=1;
//  memset(b,1,sizeof(b));
    for(int head=1;head<n;head++)//注意这里是小于不是小于等于
    {
        for(int tail=head+1;tail<=n;tail++){
            int ii=head;
            while(ii<=tail){
                x*=a[ii];
                ii++;
            }
            if(x>maxx) maxx=x;
            x=1;//贪心 
        }
        //以上遍历了所有可能情况,现在只需要求最大值就可以了

//      for(int j=1;j<=n;j++){     (原计划,但为了节约空复放弃了)
//          if(b[j]>maxx) maxx=b[j];
//      }
     } 
     cout<<maxx<<endl;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325692463&siteId=291194637