入门经典 第七章 7.7.2 最大乘积

December 14, 2012

因为范围只有18个数字,所以可以枚举起点和终点。


#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>

using namespace std;

long long int f(int a[], int start, int end) 
{
    long long int sum = 1;
    for (int i = start; i < end + 1; ++i)
    {
        sum *= a[i];
    }
    return sum;
}

int main(void)
{
    int n, a[20];
#ifndef ONLINE_JUDGE
    freopen("in", "r", stdin);
#endif
    while (~scanf("%d", &n))
    {
        for (int i = 0; i < n; ++i)
            scanf("%d", &a[i]);
        long long int sum=-1;
        for (int i = 0; i < n; ++i)
        {
            for (int j = i; j < n; ++j)
            {
                if (f(a, i, j) > sum)
                    sum = f(a, i, j);
            }
        }
        printf("%lld\n", sum);
    }

    return 0;
}

根据数据范围,估算一下能不能暴力

comments powered by Disqus