CodeForces 1406B Maximum Product

CodeForces 1406B Maximum Product

周赛的签到题。

题目大意
每组数据给出5个或以上的整数,求从中选出5个数,使它们的乘积最大。

样例输入
4
5
-1 -2 -3 -4 -5
6
-1 -2 -3 1 2 -1
6
-1 0 0 0 -1 -1
6
-9 -7 -5 -3 -2 1

样例输出
-120
12
0
945

样例解释
In the first test case, choosing a1,a2,a3,a4,a5 is a best choice: (−1)⋅(−2)⋅(−3)⋅(−4)⋅(−5)=−120.

In the second test case, choosing a1,a2,a3,a5,a6 is a best choice: (−1)⋅(−2)⋅(−3)⋅2⋅(−1)=12.

In the third test case, choosing a1,a2,a3,a4,a5 is a best choice: (−1)⋅0⋅0⋅0⋅(−1)=0.

In the fourth test case, choosing a1,a2,a3,a4,a6 is a best choice: (−9)⋅(−7)⋅(−5)⋅(−3)⋅1=945.

解题思路
分别统计数字中正数、负数、0的个数。
容易发现,如果所有数字当中非0的数字一共少于5个,那么结果肯定是0,直接输出即可。
否则先将所有的数字从小到大排列。按照数字中负数的个数进行分类讨论,分为:负数有0或1个,负数有2或3个,负数有至少4个且存在非负数,只存在负数。这4种情况分别考虑。
另外可以发现,不论是哪种情况,数字中最大的那个数字肯定要选取在其中,不管它是正数、0还是最大的负数。

AC代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
long long a[100005];
int main()
{
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int t,n;
	cin>>t;
	while(t--)
	{
		cin>>n;
		int c1=0,c2=0,c3=0;
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
			if(a[i]<0) c1++;
			if(a[i]==0) c2++;
			if(a[i]>0) c3++;
		}
		sort(a,a+n);
		if(c1+c3<5)
			cout<<"0"<<endl;
		else
		{
			if(c1==0||c1==1)
				cout<<a[n-1]*a[n-2]*a[n-3]*a[n-4]*a[n-5]<<endl;
			if(c1==2||c1==3)
			{
				if(a[0]*a[1]>a[n-4]*a[n-5])
					cout<<a[n-1]*a[n-2]*a[n-3]*a[0]*a[1]<<endl;
				else
					cout<<a[n-1]*a[n-2]*a[n-3]*a[n-4]*a[n-5]<<endl;
			}
			if(c1>=4&&c2+c3>0)
			{
				long long ans=a[n-1];
				if(a[0]*a[1]>a[n-4]*a[n-5])
					ans*=a[0]*a[1];
				else
					ans*=a[n-4]*a[n-5];
				if(a[2]*a[3]>a[n-2]*a[n-3])
					ans*=a[2]*a[3];
				else
					ans*=a[n-2]*a[n-3];
				cout<<ans<<endl;
			}
			if(c1>=5&&c2+c3==0)
				cout<<a[n-1]*a[n-2]*a[n-3]*a[n-4]*a[n-5]<<endl;
		}
	}
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

球王武磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值