题目描述
给定n个数,{x1,x2,…,xn}要求从中选出至少一个数,至多n个数,使得乘积之和最大。
输入
第一行整数n,表示有多少个数
接下来n行,每行一个整数xi,-10 ≤xi≤ 10
输出
输出一行,表示最大乘积
样例输入
Sample Input1:
3
-1
2
-4
Sample Input2:
3
3
2
-4
样例输出
Sample Output1:
8
Sample Output2:
6
数据范围限制
对于70%的数据:1 ≤ n ≤ 9
对于100%的数据: 1 ≤ n ≤ 18,-10 ≤xi≤ 10
解题思路
取的数字要大有两种方案
- 所有的正数
- 负负得正。把所有的负数的绝对值排序,选前双数个负数。
注意:如果只有一个负数,就要输出这个负数
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
int b[3000],n,t,nb;
long long Gun=1;
bool cmp(int x,int y){
return x>y;
}
int main(){
// freopen("max.in","r",stdin);
// freopen("max.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++){
int x;
scanf("%d",&x);
if(x>0)Gun*=x,++t;//所有正数
if(x<0)b[++nb]=abs(x);//存下负数的绝对值
}
sort(b+1,b+nb+1,cmp);//从大到小排序
for(int i=1;i<=nb/2*2;i++)//前偶数个负数
Gun*=b[i];
t+=nb/2*2;//t用来统计数量
if(t==0)printf("%d",-b[1]);
else printf("%lld",Gun);
}