例题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;
}

【优化】
可以在输入时加入对负数和0的统计:
(1)偶数个负数,不含0:最终结果直接等于a[0]乘到a[n-1];
(2)只要含有0 || 奇数个负数:执行循环。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值