例题7-2 最大乘积

【题目描述】
输入n个元素的序列s,找出一个连续序列的最大乘积,若最大乘积为负数,输出0表示无解。1<=n<=18,-10<=Si<=10
例如:
input:
5
2 5 -1 2 -1
output:
20
【分析】
连续子序列有两个要素:起点和终点,因此只需要枚举起点与终点即可。由于每个元素的绝对值不超过10且不超过18个元素,因此最大乘积不会超过10^18,可用long long 存储。
【代码】

#include<iostream>
#include<string>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1000 + 10;
int main()
{
	int n;
	while (scanf("%d", &n) != EOF)
	{
		int * a;
		a = new int[n];
		for (int i = 0;i < n;i++)
			scanf("%d", &a[i]);
		int max_sum = 0;
		for (int i = 0;i < n;i++)
		{
			int cnt = 1;
			for (int j = i;j < n;j++)
			{
				cnt *= a[j];
				if (cnt > max_sum) max_sum = cnt;
			}
		}
		if (max_sum < 0) cout << "0" << endl;
		else cout << max_sum << endl;
		delete[]a;
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cprimesplus/article/details/84349595
今日推荐