首页 > 其他 > 详细

ACM----CodeForces - 1406B Maximum Product

时间:2021-02-08 22:18:17      阅读:42      评论:0      收藏:0      [点我收藏+]

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 }

 

ACM----CodeForces - 1406B Maximum Product

原文:https://www.cnblogs.com/jin0622/p/14390059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!