题目描述
输入n个元素组成的序列S,你需要找出一个乘积最大的连续子序列。如果这个最大的乘积不是正数,应输出-1(表示无解)。1<=n<=18,-10<=Si<=10.
样例输入:
3
2 4 -3
5
2 5 -1 2 -1
样例输出:
8
20
分析:连续子序列有两个要素:一个起点一个终点,因此只要枚举起点和终点即
Si的绝对值不超过10,一共不超过18个元素所以最大值不超过1e18,可以用long long存
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
int a[20];
while (cin >> n)//多组数据测试
{
long long max1 = -1;
long long temp = 1;
for (int i = 0; i < n; i++)cin >> a[i];
for (int i = 0; i < n; i++)//枚举起点
{
temp = 1;//每一个子序列都要把temp还原成1
for (int j = i; j < n; j++)//枚举终点
{
temp *= a[j];
max1 = max(max1, temp);//保存每段子序列的最大值
}
}
if (max1 < 0)//如果是负数就输出-1
cout << -1 << endl;
else
cout << max1 << endl;
}
return 0;
}