Given a sequence of integers S = {S1, S2, . . . , Sn}, you should determine what is the value of the maximum positive product involving consecutive terms of S. If you cannot find a positive sequence, you should consider 0 as the value of the maximum product.
Input
Each test case starts with 1 ≤ N ≤ 18, the number of elements in a sequence. Each element Si is an integer such that −10 ≤ Si ≤ 10. Next line will have N integers, representing the value of each element in the sequence. There is a blank line after each test case. The input is terminated by end of file (EOF).
Output
For each test case you must print the message: ‘Case #M: The maximum product is P.’, where M is the number of the test case, starting from 1, and P is the value of the maximum product. After each test case you must print a blank line.
Sample Input
3
2 4 -3
5
2 5 -1 2 -1
Sample Output
Case #1: The maximum product is 8.
Case #2: The maximum product is 20.
问题链接:UVA11059 Maximum Product。
题意简述:
输入n个整数序列,有正有负,求这个序列中最大连续累乘的子序列,其最大的值为多少。如果结果为负数,则输出0。
问题分析:
如果整数序列中有0,则用0分段然后分别计算。对于每个分段(可能只有一个分段),其中没有0,如果其中有偶数个负数,则将分段中所有的数相乘就是所求结果。如果分段中有奇数个负数,那么最大的累乘出现在第1个负数的右边开始的子序列或从开始到最后1个负数左边的子序列。
程序说明:(略)
AC的C语言程序如下:
/* UVA11059 Maximum Product */
#include <stdio.h>
int main(void)
{
int n, val, caseno=0, flag;
long long ans, max, afternegativemax;
while(scanf("%d", &n) != EOF) {
ans = 0;
max = 1;
afternegativemax = 1;
flag = 0;
while(n--) {
scanf("%d", &val);
if(val == 0) {
max = 1;
afternegativemax = 1;
flag = 0;
} else {
max *= val;
if(max > ans)
ans = max;
if(flag) {
afternegativemax *= val;
if(afternegativemax > ans)
ans = afternegativemax;
}
if(val < 0)
flag = 1;
}
}
printf("Case #%d: The maximum product is %lld.\n\n", ++caseno, ans);
}
return 0;
}