ACM----CodeForces Round #670 (Div. 2)B. Maximum Product

You are given an array of integers 𝑎1,𝑎2,…,𝑎𝑛. Find the maximum possible value of 𝑎𝑖𝑎𝑗𝑎𝑘𝑎𝑙𝑎𝑡 among all five indices (𝑖,𝑗,𝑘,𝑙,𝑡) (𝑖<𝑗<𝑘<𝑙<𝑡).

Input
The input consists of multiple test cases. The first line contains an integer 𝑡 (1≤𝑡≤2⋅104) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer 𝑛 (5≤𝑛≤105) — the size of the array.

The second line of each test case contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (−3×103≤𝑎𝑖≤3×103) — given array.

It’s guaranteed that the sum of 𝑛 over all test cases does not exceed 2⋅105.

Output
For each test case, print one integer — the answer to the problem.

Example
inputCopy
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
outputCopy
-120
12
0
945
Note
In the first test case, choosing 𝑎1,𝑎2,𝑎3,𝑎4,𝑎5 is a best choice: (−1)⋅(−2)⋅(−3)⋅(−4)⋅(−5)=−120.

In the second test case, choosing 𝑎1,𝑎2,𝑎3,𝑎5,𝑎6 is a best choice: (−1)⋅(−2)⋅(−3)⋅2⋅(−1)=12.

In the third test case, choosing 𝑎1,𝑎2,𝑎3,𝑎4,𝑎5 is a best choice: (−1)⋅0⋅0⋅0⋅(−1)=0.

In the fourth test case, choosing 𝑎1,𝑎2,𝑎3,𝑎4,𝑎6 is a best choice: (−9)⋅(−7)⋅(−5)⋅(−3)⋅1=945.

题目大意:在给定序列中选五个数使得乘积最大。

解题思路:先将给定序列进行排序,排序后求序列左侧五个数乘积,左侧四个数和右侧一个数乘积,左侧三个数和右侧两个数乘积..........最后求右侧五个数的乘积,在这六个数中取最大值。

 1 #include<iostream>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 int main(){
 6     int n,m,f;
 7     long long int a[100000],s,result;
 8     cin >> n;
 9     while(n--){
10         cin >> m;
11         for(int i=0;i<m;i++)
12             cin >> a[i];
13         sort(a,a+m);
14         result=a[0]*a[1]*a[2]*a[3]*a[4];   
15         for(int i=4;i>=0;i--){
16             s=1;
17             for(int j=0;j<i;j++)   
18                 s*=a[j];
19             for(int j=0;j<5-i;j++)    
20                 s*=a[m-1-j];
21             result=max(result,s);     
22         }
23         cout <<result<< endl;
24     }
25     return 0;
26 }

 

posted @ 2021-02-08 18:52  AA、  阅读(77)  评论(0编辑  收藏  举报