题目链接:UVa 11509
题意:
输入n个元素组成的序列S,你需要找出一个乘积最大的连续子序列。如果这个最大的乘积不是正数,应输出0(表示无解)。1<=n<=18,-10<=S[i]<=10。
分析:
两层循环对每个s[i]求最大连续子序列乘积,逐个取最大即可。
注意:
- C++中 long long 不能用%I64d输出。
CODE:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
int n, a[20],cases=0;
long long ans, tmp;
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
#endif
while (cin >> n)
{
for (int i = 0; i < n; i++)
cin >> a[i];
ans = 0;
for (int i = 0; i < n; i++)
{
tmp = 1;
for (int j = i; j < n; j++)
{
tmp *= a[j];
ans = max(ans, tmp);
}
}
printf("Case #%d: The maximum product is %lld.\n\n", ++cases, ans);
}
return 0;
}
附一个O(n)的解法。原博地址:UVa 11059
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int data[20];
int main()
{
int n,t = 1;
while (cin >> n) {
for (int i = 1 ; i <= n ; ++ i)
cin >> data[i];
long long max = 0,neg = 0,pos = 0,tem;
for (int i = 1 ; i <= n ; ++ i) {
if (data[i] == 0)
neg = pos = 0;
else if (data[i] > 0) {
pos = pos*data[i];
neg = neg*data[i];
if (!pos) pos = data[i];
}else if (data[i] < 0) {
tem = pos*data[i];
pos = neg*data[i];
neg = tem;
if (!neg) neg = data[i];
}
if (max < pos && data[i])
max = pos;
}
cout << "Case #" << t ++ << ": The maximum product is " << max << ".\n\n";
}
return 0;
}