(纪中)2090. 最大值【数学】

(File IO): input:max.in output:max.out
时间限制: 1000 ms 空间限制: 262144 KB 具体限制
Goto ProblemSet


题目描述
给定 n n 个数, x 1 , x 2 , . . . , x n {x1,x2,...,xn} 要求从中选出至少一个数,至多 n n 个数,使得乘积之和最大。


输入
第一行整数 n n ,表示有多少个数
接下来 n n 行,每行一个整数 x i , 10 x i 10 xi,-10 ≤xi≤ 10

输出
输出一行,表示最大乘积


样例输入
Sample Input1:
3
-1
2
-4

Sample Input2:
3
3
2
-4


样例输出
Sample Output1:
8
Sample Output2:
6


数据范围限制
对于 70 70% 的数据: 1 n 9 1 ≤ n ≤ 9
对于 100 100% 的数据: 1 n 18 10 x i 10 1 ≤ n ≤ 18,-10 ≤xi≤ 10


解题思路:
我们在输入时,把不是0的数乘起来,并统计0的个数,把最大的负数记录下来。
最后我们可以分为几种情况:
1.如果ans小于0,那么ans=ans/max(最大的负数)。
2.如果全都是0,那么就输出0,否则输出ans。


代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int n,a;
long long ans,t,maxn=-1000000;
int main()
{
     freopen("max.in","r",stdin);
	 freopen("max.out","w",stdout);
	 scanf("%d",&n);
	 ans=1;
	 for(int i=1;i<=n;i++)
	 {
	 	scanf("%d",&a);
	 	if(a!=0)//直接把不是0的数乘起来
	 	ans*=a;
	 	else 
		t++;//统计0的个数
	 	if(a<0&&maxn<a) //记录最大的负数
		maxn=a;
	 }
    if (ans<0&&ans!=maxn) ans=ans/maxn;//情况1
    if(t==n) cout<<0;//情况2
    else cout<<ans;
}
发布了73 篇原创文章 · 获赞 5 · 访问量 1822

猜你喜欢

转载自blog.csdn.net/kejin2019/article/details/104196751
今日推荐