Maximum Product

You are given an array of integers a1,a2,…,an�1,�2,…,��. Find the maximum possible value of aiajakalat���������� among all five indices (i,j,k,l,t)(�,�,�,�,�) (i<j<k<l<t�<�<�<�<�).

Input

The input consists of multiple test cases. The first line contains an integer t� (1≤t≤2⋅1041≤�≤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 n� (5≤n≤1055≤�≤105) — the size of the array.

The second line of each test case contains n� integers a1,a2,…,an�1,�2,…,�� (−3×103≤ai≤3×103−3×103≤��≤3×103) — given array.

It's guaranteed that the sum of n� over all test cases does not exceed 2⋅1052⋅105.

Output

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

Sample 1

InputcopyOutputcopy
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
-120
12
0
945

Note

In the first test case, choosing a1,a2,a3,a4,a5�1,�2,�3,�4,�5 is a best choice: (−1)⋅(−2)⋅(−3)⋅(−4)⋅(−5)=−120(−1)⋅(−2)⋅(−3)⋅(−4)⋅(−5)=−120.

In the second test case, choosing a1,a2,a3,a5,a6�1,�2,�3,�5,�6 is a best choice: (−1)⋅(−2)⋅(−3)⋅2⋅(−1)=12(−1)⋅(−2)⋅(−3)⋅2⋅(−1)=12.

In the third test case, choosing a1,a2,a3,a4,a5�1,�2,�3,�4,�5 is a best choice: (−1)⋅0⋅0⋅0⋅(−1)=0(−1)⋅0⋅0⋅0⋅(−1)=0.

In the fourth test case, choosing a1,a2,a3,a4,a6�1,�2,�3,�4,�6 is a best choice: (−9)⋅(−7)⋅(−5)⋅(−3)⋅1=945(−9)⋅(−7)⋅(−5)⋅(−3)⋅1=945.

题目解读:

要求在给定的整数数组中找到五个索引(i, j, k, l, t),满足 i < j < k < l < t,并计算这五个索引对应的数组元素的最大乘积 aiajakalat。

解题思路:

先将数组从小到大排序:

a1 a2 a3 a4 a5 a6 a7.......... 0 a-7 a-6 a-5 a-4 a-3 a-2 a-1

0在中间,左边负数,右边正数

最大乘积可以可能是以下几种情况:①最大的五个数的乘积②最小的五个数的乘积③最左边2个数*最右边3个④最左边4个*最右边1个

代码:python

def max_product(arr):  
    # 对数组进行排序  
    arr.sort()  
      
    mul1 = arr[-1] * arr[-2] * arr[-3] * arr[-4] * arr[-5] 
    mul2 = arr[0] * arr[1] * arr[2] * arr[3] * arr[4]  
        
    min_2 = arr[0] * arr[1]  
    max_3 = arr[-1] * arr[-2] * arr[-3]  
    mul3 = min_2 * max_3  
    min_4=arr[0] * arr[1] * arr[2] *arr[3]
    mul4=min_4*arr[-1]
      
    # 返回四者中的最大值  
    return max(mul1,mul2,mul3,mul4)  
  
# 读取输入并处理每个测试用例  
t = int(input().strip())  # 测试用例数量  
for _ in range(t):  
    n = int(input())   
    arr = list(map(int, input().split()))   
    print(max_product(arr))  

运行结果:

4                                                      
5
-1 -2 -3 -4 -5
-120
6
-1 -2 -3 1 2 -1
12
6
-1 0 0 0 -1 -1
0
6
-9 -7 -5 -3 -2 1
945

  • 18
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值