EPS/2024/02/12-02-24/a.py

75 lines
1.8 KiB
Python

def product(l):
if l == []:
return 1
return l[0]*product(l[1:])
def once():
input()
ai = [int(i) for i in input().split()]
ai_p = [a for a in ai if a > 0]
ai_n = [a for a in ai if a < 0]
contains0 = (0 in ai)
ai_p.sort(reverse=True)
ai_n.sort()
if ai_p == []: # all neg or null
if contains0:
return 0
return product(ai_n[-5:])
elif len(ai_n)+len(ai_p) < 5:
return product(ai)
elif len(ai_n)+len(ai_p) == 5:
p = product(ai_n)*product(ai_p)
if p < 0 and contains0:
return 0
return p
else:
# selected = [ai_p[0]]
i_n = 0
i_p = 1
prod = ai_p[0]
for _ in range(2):
if i_n + 2 > len(ai_n) and i_p + 2 <= len(ai_p):
prod *= ai_p[i_p]*ai_p[i_p+1]
# selected.append(ai_p[i_p])
# selected.append(ai_p[i_p+1])
i_p+=2
elif i_p + 2 > len(ai_p) and i_n + 2 <= len(ai_n):
prod *= ai_n[i_n]*ai_n[i_n+1]
# selected.append(ai_n[i_n])
# selected.append(ai_n[i_n+1])
i_n+=2
elif i_p +1 == len(ai_p) and i_n+1 == len(ai_n):
prod *= ai_p[-1]*ai_n[-1]
else:
pp = ai_p[i_p]*ai_p[i_p+1]
pn = ai_n[i_n]*ai_n[i_n+1]
if pp > pn:
prod *= pp
# selected.append(ai_p[i_p])
# selected.append(ai_p[i_p+1])
i_p += 2
else:
prod *= pn
# selected.append(ai_n[i_n])
# selected.append(ai_n[i_n+1])
i_n += 2
return prod
def main():
count = int(input())
for _ in range(count):
print(once())
main()