UVA11059 Maximum Product

问题链接UVA11059 Maximum Product基础级练习题,用C语言编写程序。

题意简述:输入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.

", ++caseno, ans);
    }

    return 0;
}


原文地址:https://www.cnblogs.com/tigerisland/p/7564490.html