题意 求最大连续子序列的积
思路 本题可以暴力枚举起始和终止位置,O(n^2),不过为了练习,写了一个O(n)的算法,总体来算法不过简练
大致思路,就是正反两个方向遍历数组,预处理对所有负数的位置,保存在下一个0前还有几个负数,在上一个0后还有几个负数,然后双向遍历,遇到正数,更新sum,遇到0,清空sum,更新max,遇到负数,要判断若当前sum是负数或者该负数后,在下一个0前还有负数,则更新sum,否则清空sum。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 20
typedef long long ll;
typedef pair<int,int> Pll;
#define fi first
#define se second
#define MP make_pair
int n;
ll max1 = 0;
ll a[MAX];
Pll b[MAX];
int main()
{
int i,j;
int T = 0;
while(scanf("%d",&n) == 1)
{
for(i=0;i<n;i++)
scanf("%lld",&a[i]);
T++;
max1 = 0;
int count = 0;
for(i=n-1;i>=0;i--)
{
if(a[i] < 0)
b[i].fi = count++;
else if(a[i] == 0)
count = 0;
}
count = 0;
for(i=0;i<n;i++)
{
if(a[i] < 0)
b[i].se = count++;
else if(a[i] == 0)
count = 0;
}
ll sum = 1;
bool flag = 0;
for(i=0;i<n;i++)
{
if(a[i] > 0)
{
sum *= a[i];
flag = 1;
}
else if(a[i] == 0)
{
max1 = max(sum,max1);
sum = 1;
}
else
{
if(sum < 0 || b[i].fi > 0)
{
sum *= a[i];
flag = 1;
}
else
{
max1 = max(sum,max1);
sum = 1;
}
}
}
max1 = max(sum,max1);
sum = 1;
for(i=n-1;i>=0;i--)
{
if(a[i] > 0)
{
sum *= a[i];
flag = 1;
}
else if(a[i] == 0)
{
max1 = max(sum,max1);
sum = 1;
}
else
{
if(sum < 0 || b[i].se > 0)
{
sum *= a[i];
flag = 1;
}
else
{
max1 = max(sum,max1);
sum = 1;
}
}
}
max1 = max(sum,max1);
if(flag == 0)
printf("Case #%d: The maximum product is 0.\n\n",T);
else
printf("Case #%d: The maximum product is %lld.\n\n",T,max1);
}
return 0;
}