Codeforces Round #670 (Div. 2)B. Maximum Product(5個數乘積最大)
阿新 • • 發佈:2020-09-14
地址:http://codeforces.com/contest/1406/problem/B
題意:
給出n個數,找出5個數,使得乘積最大化。
解析:
5個數,分情況:
負 正
0 5
1 4
2 3
3 2
4 1
5 0
可以發現,對於負數個數為1,3的時候,這個時候結果是負數
假設這個時候n==5,那麼就是從頭乘到底
假設n>5,那麼多出來那個數,要麼是正數,要麼是負數,要麼是0。一定有辦法把結果變成0或正數,所以可以把它們歸到其他類裡。
所以對於n>5的時候,負數只能取0,2,4。發現這些情況中,最優解就是從排好序的陣列中首尾取5個。
所以可以列舉首部取的下標i,這裡規定,i=1,首部取了0個,i=2,首部取了1個,i本身不取,所以i要列舉到6
思維過程:
列舉->發現無效組合->轉化為求首尾取5個的最大乘積
程式碼:
#include<bits/stdc++.h> #include<map> #include<iostream> #include<cstring> #include<cmath> using namespace std; typedef long long ll; const int maxn=1e5+10; const int maxn2=1e9+10; const int mod=1e9+10; int a[maxn]; struct node {int x1,y1,x2,y2; }st[maxn]; int main() { int t; cin>>t; while(t--) { int n; cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; ll maxx=-1e18; sort(a+1,a+1+n); for(int i=1;i<=6;i++) { ll md=1; for(int j=1;j<i;j++) md*=a[j]; for(int j=n;j>=n+i-5;j--) md*=a[j]; // cout<<i<<" "<<md<<endl; maxx=max(maxx,md); } cout<<maxx<<endl; } }