给一个数字集合{ S1,S2,…,Sn },请从这个数字集合里找出一段连续数字,使他们的乘积是最大的。1n
18,-10
Si
10。
样例输入:
3
2 4 -3
5
2 5 -1 2 -1
3
-9 -7 -8
2
1 -1
1
-9
样例输出
Case #1: The maximum product is 8.
Case #2: The maximum product is 20.
Case #3: The maximum product is 63.
Case #4: The maximum product is 1.
题意:
求出给定数列的某一连续子段的乘积最大值且为正数
分析:
由于n的范围很小且si也很小,所以我们可以直接枚举该数列的所有子段并求出他们的乘积的最大值,注意最大值应该用long long类型,因为最大值最大为10^18
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N=20;
int a[N];
int main()
{
int n;
while(cin>>n&&n){
ll maxn=0,ans=1;
for(int i=0;i<n;++i){
cin>>a[i];
}
//i表示子段头,j表示子段尾
for(int i=0;i<n;++i){
ans=1;
for(int j=i;j<n;++j){
ans*=a[j];
maxn=max(maxn,ans);
}
}
cout<<maxn<<endl;
}
return 0;
}