UVa 11509 Maximum Product(最大乘积)

题目链接:UVa 11509

题意:

输入n个元素组成的序列S,你需要找出一个乘积最大的连续子序列。如果这个最大的乘积不是正数,应输出0(表示无解)。1<=n<=18,-10<=S[i]<=10。

分析:

两层循环对每个s[i]求最大连续子序列乘积,逐个取最大即可。

注意:

  • C++中 long long 不能用%I64d输出。



CODE:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;

int n, a[20],cases=0;
long long ans, tmp;

int main()
{
#ifdef LOCAL
	freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
#endif
	while (cin >> n)
	{
		for (int i = 0; i < n; i++)
			cin >> a[i];
		ans = 0;
		for (int i = 0; i < n; i++)
		{
			tmp = 1;
			for (int j = i; j < n; j++)
			{
				tmp *= a[j];
				ans = max(ans, tmp);
			}
		}
		printf("Case #%d: The maximum product is %lld.\n\n", ++cases, ans);
	}
	return 0;
}

附一个O(n)的解法。原博地址:UVa 11059


#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

int data[20];

int main()
{
	int n,t = 1;
	while (cin >> n) {
		for (int i = 1 ; i <= n ; ++ i)
			cin >> data[i];
		long long max = 0,neg = 0,pos = 0,tem;
		for (int i = 1 ; i <= n ; ++ i) {
			if (data[i] == 0) 
				neg = pos = 0;
			else if (data[i] > 0) {
				pos = pos*data[i];
				neg = neg*data[i];
				if (!pos) pos = data[i];
			}else if (data[i] < 0) {
				tem = pos*data[i];
				pos = neg*data[i];
				neg = tem;
				if (!neg) neg = data[i];
			}
			if (max < pos && data[i])
				max = pos;
		}
		
		cout << "Case #" << t ++ << ": The maximum product is " << max << ".\n\n";	
	}
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值