Title Description
A given number n, {x1, x2, ..., xn} which selects at least a number of requirements, up to the number n, such that the maximum sum of products.
Entry
The first line integer n, the number represents the number of
the next n lines, each line an integer xi, -10 ≤xi≤ 10
Export
Output line, represents the maximum product
Sample input
Sample Input1:
3
-1
2
-4
Sample Input2:
3
3
2
-4
Sample Output
Sample Output1:
8
Sample Output2:
6
hint
For 70% of the data: 1 ≤ n ≤ 9
to 100% of the data: 1 ≤ n ≤ 18, -10 ≤xi≤ 10
analysis
This question to open long long !!
input, we judge three cases:
- xi> 0 then use it directly by a sum
- xi <0 In this case the number of recording a negative We f, b [f] save up to negative, but also with the product of all negative s1 calculated.
- xi = 0 to skip
and then we do a sort the array b (small to large)
if s1> 0, direct output * SUM s1;
! If f% 2 = 0, then we ignore the biggest negative number (absolute minimum), take up with the sum.
The Code!
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
long long n,f,s=1,s1=1,a[20];
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(n==1)
{
cout<<x;
return 0;
}
if(x<0)
{
f++;
a[f]=x;
s1*=x;
}
if(x>0) s*=x;
}
for(int i=1;i<=f-1;i++)
for(int j=i+1;j<=f;j++)
if(a[i]>a[j]) swap(a[i],a[j]);
if(s1>0&&f%2==0) cout<<s1*s;
else if(f%2!=0)
{
for(int i=1;i<=f-1;i++)
{
s*=a[i];
}
cout<<s;
}
fclose(stdin);
fclose(stdout);
return 0;
}