Problem:


Score : 500 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.

Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Constraints

1 \leq K \leq N \leq 2\times 10^5

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 \ldots A_N

Output

Print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Sample Input 1

4 2
1 2 -3 -4

Sample Output 1

12

The possible products of the two chosen elements are 2, -3, -4, -6, -8, and 12, so the maximum product is 12.

Sample Input 2

4 3
-1 -2 -3 -4

Sample Output 2

1000000001

The possible products of the three chosen elements are -24, -12, -8, and -6, so the maximum product is -6.

We print this value modulo (10^9+7), that is, 1000000001.

Sample Input 3

2 1
-1 1000000000

Sample Output 3

1000000000

The possible products of the one chosen element are -1 and 1000000000, so the maximum product is 1000000000.

Sample Input 4

10 10
1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1

Sample Output 4

999983200

Be sure to print the product modulo (10^9+7).



Sample input:
4 2
1 2 -3 -4


Sample output:
12

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
A=sorted(list(map(int,input().split())))
mod=10**9+7

if A[-1]<0 and k%2==1:
    now=1
    for i in range(k):
        now*= A[-i-1]
        now%=mod
    print(now) ;exit()

l=0 ; r=n-1
ans=1
if k%2==1:
    ans=A[-1]
    r-=1

for i in range(k//2):
    mi=A[l]*A[l+1]
    pl=A[r]*A[r-1]
    if mi>pl:
        ans*= mi%mod
        l+=2
    else:
        ans*= pl%mod
        r-=2
print(ans%mod)

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
A.sort()
div=7+10**9
ans=1
t=0
i,j=0,N-1

if A[-1]<0 and K%2==1:
    for i1 in range(N-K,N):
        ans*=A[i1]
else:
    while t<K-1:
        if A[i]*A[i+1]>A[j]*A[j-1]:
            ans*=A[i]*A[i+1]
            i+=2
            t+=2
        else:
            ans*=A[j]
            j+=-1
            t+=1
    if t==K-1:
        ans*=A[j]

print(ans%div)

Submission status: Time Limit Exceeded

Solution code:
mod=1000000007
n,k=map(int, input().split())
lst=list(map(int, input().split()))
lst=sorted(lst)
p=1
if lst[-1]==0 and k%2!=0:
    print(0)
elif lst[-1]<0 and k%2!=0:
    for i in range(n-1,n-k-1,-1):
        #print(p)
        p*=lst[i]
    #print(p)
    print(p%mod)
else:
    j=n-1
    if k%2!=0:
        p*=lst[j]
        k-=1
        j-=1
    k=k//2
    i=0
    for x in range(k):
        if lst[i]*lst[i+1]>lst[j]*lst[j-1]:
            p*=(lst[i]*lst[i+1])
            i+=2
        else:
            p*=(lst[j]*lst[j-1])
            j-=2
    #print(p)
    print(p%mod)

Submission status: Time Limit Exceeded

Solution code:
INF = 10**9 + 7
N, K = map(int, input().split())
A = list(map(int, input().split()))
plus_lst, minus_lst = [], []
plus, minus = 0, 0
ans = 1
if K == N:
  for i in A:
    ans *= i
  ans %= INF
  print(ans)
else:
  for _ in range(N):
    a = A.pop()
    if a >= 0:
      plus_lst += [a]
      plus += 1
    else:
      minus_lst += [-a]
      minus += 1
  if K % 2 and plus == 0:
    minus_lst = sorted(minus_lst)
    for i in range(K):
      ans *= minus_lst[i]
    ans *= -1
    ans %= INF
    print(ans)
  else:
    plus_lst = sorted(plus_lst, reverse=True)
    minus_lst = sorted(minus_lst, reverse=True)
    a = plus_lst.pop(0) if plus_lst else 0
    b = plus_lst.pop(0) if plus_lst else 0
    c = minus_lst.pop(0) if minus_lst else 0
    d = minus_lst.pop(0) if minus_lst else 0
    for i in range(K//2):
      plus_num = a * b
      minus_num = c * d
      if plus_num > minus_num:
        ans *= plus_num
        a = plus_lst.pop(0) if plus_lst else 0
        b = plus_lst.pop(0) if plus_lst else 0
      else:
        ans *= minus_num
        c = minus_lst.pop(0) if minus_lst else 0
        d = minus_lst.pop(0) if minus_lst else 0
    if K % 2 == 1:
      ans *= a
    ans %= INF
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
MOD=10**9+7

def moddiv(a,m):
    return pow(a,m-2,m)

def solve():
    res=-10**30
    minus,plus,zero=[],[],[]
    for i in range(N):
        if A[i]<0:
            minus.append(A[i])
        elif A[i]>0:
            plus.append(A[i])
        else:
            zero.append(A[i])
    cump=1
    plus.sort()
    minus.sort()
    for i in range(len(plus)):
        cump=cump*plus[i]%MOD
    j=0
    i=0
    cumm=1
    while(j<=min(len(minus),K)):
        if j>0:
            cumm=cumm*minus[j-1]*minus[j-2]%MOD
            newm=minus[j-1]*minus[j-2]
        if K-j>len(plus):
            j+=2
            continue
        oldp=1
        while(K-j<len(plus)-i):
            cump=cump*moddiv(plus[i],MOD)%MOD
            oldp*=plus[i]
            i+=1
        if j>0:
            if newm>oldp:
                res=cumm*cump%MOD
        else:
            res=max(res,cumm*cump%MOD)
        j+=2
    if res!=-10**30:
        return res
    if len(zero)>0:
        return 0
    li=minus+plus
    li.sort(key=lambda x:abs(x))
    res=1
    for i in range(K):
        res=res*li[i]%MOD
    return res
N,K=map(int,input().split())
A=list(map(int,input().split()))

if min(A)>=0:
    res=1
    A.sort(reverse=True)
    for i in range(K):
        res=res*A[i]%MOD
elif max(A)<=0:
    res=1
    if not K%2:
        A.sort()
        for i in range(K):
            res=res*A[i]%MOD
    else:
        A.sort(reverse=True)
        for i in range(K):
            res=res*A[i]%MOD
else:
    res=solve()
print(res)

Submission status: Time Limit Exceeded

Solution code:
import itertools
from functools import reduce
from operator import mul
n, k = map(int, input().split())
lst = list(map(int, input().split()))
lst2 = list(itertools.combinations(lst, k))
#print(lst2)

anslst = []
for i in range(len(lst2)):
	seki = reduce(mul, lst2[i])
	anslst.append(seki)

#print(anslst)
tei = 10 ** 9 + 7
print(max(anslst) % tei)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

def main():
    n,k = map(int, input().split())
    A = list(map(int, input().split()))
    ans = 1
    
    if k == n:
        for a in A:
            ans *= a
        print(ans%(10**9+7))
        
    elif k%2==1 and all([a<0 for a in A]):
        A = sorted(A, key=lambda x:abs(x))
        for a in A[:k]:
            ans*=a
        print(ans%(10**9+7))

    else:
        A = sorted(A, key=lambda x:abs(x), reverse=True)
        x1, x2 = None, None
        for a in A[:k]:
            ans*=a
            if a >= 0 and (x1 is None or a < x1): x1 = a
            if a < 0 and (x2 is None or a > x2): x2 = a
            
        if ans >= 0:
            print(ans%(10**9+7))
        else:
            y1, y2 = None, None
            for a in A[k:]:
                if a < 0 and (y1 is None or a < y1): y1 = a
                if a >= 0 and (y2 is None or a > y2): y2 = a
            
            tmp = [ans]
            if x1!=None and y1!=None:
                tmp.append(ans//x1*y1)
            if x2!=None and y2!=None:
                tmp.append(ans//x2*y2)
            ans = max(tmp)
            print(ans%(10**9+7))            
main()

Submission status: Time Limit Exceeded

Solution code:
def can_plus(PLUSS, MINUSS, K):
    PLUSS = list(reversed(sorted(PLUSS)))
    MINUSS = list(sorted(MINUSS))

    cumul = 1

    plus_idx = 0
    minus_idx = 0

    cnt = 0
    while True:
        if cnt == K:
            break
        elif cnt == K-1:
            cumul = cumul * PLUSS[plus_idx]
            plus_idx += 1
            cnt += 1
        elif minus_idx >= len(MINUSS) - 1:
            cumul = cumul * PLUSS[plus_idx]
            plus_idx += 1
            cnt += 1
        elif plus_idx >= len(PLUSS) - 1:
            cumul = cumul * MINUSS[minus_idx] * MINUSS[minus_idx + 1]
            minus_idx += 2
            cnt += 2
        elif (plus_idx == len(PLUSS) - 2) and ((K - cnt) % 2) == 1:
            cumul = cumul * PLUSS[plus_idx]
            plus_idx += 1
            cnt += 1
        elif (plus_idx <= len(PLUSS) - 2) and (minus_idx <= len(MINUSS) - 2):
            plus_pair = PLUSS[plus_idx] * PLUSS[plus_idx + 1]
            minus_pair = MINUSS[minus_idx] * MINUSS[minus_idx + 1]
            if plus_pair >= minus_pair:
                cumul = cumul * plus_pair
                plus_idx += 2
            else:
                cumul = cumul * minus_pair
                minus_idx += 2
            cnt += 2
        else:
            cnt += 1
    return cumul


def main():
    a = input()
    aa = a.split()
    K = int(aa[1])

    b = input()
    A = [int(bb) for bb in b.split()]

    PLUSS = []
    MINUSS = []
    ZEROS = []
    for a in A:
        if a > 0:
            PLUSS.append(a)
        elif a < 0:
            MINUSS.append(a)
        else:
            ZEROS.append(a)

    # ゼロ以下になることが避けられない場合
    if len(MINUSS) + len(PLUSS) < K:
        print("0")
        return
    elif len(PLUSS) == 0 and (K % 2) == 1:
        if len(ZEROS) > 0:
            print("0")
            return
        else:
            MINUSSS = list(reversed(sorted(MINUSS)))
            cumul = 1
            for i in range(K):
                cumul = cumul * MINUSSS[i]
    elif len(MINUSS) + len(PLUSS) == K:
        cumul = 1
        for a in A:
            cumul = cumul * a
    else:
        cumul = can_plus(PLUSS, MINUSS, K)

    DIV = 1_000_000_007
    print(cumul % DIV)


main()

Submission status: Time Limit Exceeded

Solution code:
import itertools
import numpy as np

n, k = map(int, input().split())
a = [int(i) for i in input().split()]
ans = -float("inf")
for nums in itertools.combinations(a, k):
    p = 1
    for n in nums:
        p *= n
    ans = max(p, ans)
print(ans % (10 ** 9 + 7))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.buffer.readline

def main():
    N, K = map(int,input().split())
    A = list(map(int,input().split()))
    A.sort()
    l, r = 0, N-1
    MOD = 10**9+7
    if K == N:
        ans = 1
        for num in A:
            ans *= num
        print((ans+MOD)%MOD)
        exit()
    elif A[-1] < 0 and K%2 == 1:
        ans = 1
        for i in range(K):
            ans *= A[-i-1]
        ans = (ans+MOD)%MOD
        print(ans)
        exit()
    ans = 1
    if K%2 == 1:
        ans *= A[-1]
        r -= 1
    for _ in range(K//2):
        nl = A[l]*A[l+1]
        nr = A[r]*A[r-1]
        if nl > nr:
            ans *= nl
            l += 2
        else:
            ans *= nr
            r -= 2
    print((ans+MOD)%MOD)
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.buffer.readline

def main():
    N, K = map(int,input().split())
    A = list(map(int,input().split()))
    A.sort()
    l, r = 0, N-1
    MOD = 10**9+7
    if K == N:
        ans = 1
        for num in A:
            ans *= num
        print((ans+MOD)%MOD)
        exit()
    elif A[-1] < 0 and K%2 == 1:
        ans = 1
        for i in range(K):
            ans *= A[-i-1]
        ans = (ans+MOD)%MOD
        print(ans)
        exit()
    ans = 1
    if K%2 == 1:
        ans *= A[-1]
        r -= 1
    for _ in range(K//2):
        nl = A[l]*A[l+1]
        nr = A[r]*A[r-1]
        if nl > nr:
            ans *= nl
            l += 2
        else:
            ans *= nr
            r -= 2
        ans = (ans+MOD)%MOD
    print(ans)
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
"""
E.
"""
from functools import reduce
from collections import deque


def prod(x, y):
    return x * y % MOD

    
N, K = map(int, input().split())
a_list = list(map(int, input().split()))
a_list.sort(reverse=True)
# abs_a_list = sorted(a_list, key=abs, reverse=True)
MOD = 10**9 + 7

if K%2 == 1:
    flg = True
    for a in a_list:
        if a >= 0:
            flg = False
            break
    if flg:
        print(reduce(prod, a_list[:K]))
        exit()

S = []
a_list = deque(a_list)
for _ in range(K//2):
    if a_list[0]*a_list[1] > a_list[-1]*a_list[-2]:
        S.append(a_list.popleft())
        S.append(a_list.popleft())
    else:
        S.append(a_list.pop())
        S.append(a_list.pop())
    if 0 in S:
        print(0)
        exit()
        
if K%2 == 1:
    S.append(a_list.popleft())
ans = reduce(prod, S)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
"""
E.
"""
from functools import reduce
from collections import deque


def prod(x, y):
    return x * y % MOD

    
N, K = map(int, input().split())
a_list = list(map(int, input().split()))
a_list.sort(reverse=True)
abs_a_list = sorted(a_list, key=abs, reverse=True)
MOD = 10**9 + 7

if K%2 == 1:
    flg = True
    for a in a_list:
        if a >= 0:
            flg = False
            break
    if flg:
        print(reduce(prod, a_list[:K])%MOD)
        exit()

# ans2
S = []
for _ in range(K//2):
    if a_list[0]*a_list[1] >= a_list[-1]*a_list[-2]:
        S.append(a_list.pop(0))
        S.append(a_list.pop(0))
    else:
        S.append(a_list.pop(-1))
        S.append(a_list.pop(-1))
if K%2 == 1:
    S.append(a_list.pop(0))

ans = reduce(prod, S)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations
import functools 
mod = (10**9)+7
n,k = map(int,input().split())
arr=list(map(int,input().split()))
perm = combinations(arr, k) 
  
ina = [functools.reduce(lambda a,b : a*b,i) for i in list(perm)]
print (max(ina)%mod)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
pos = []
neg = []
for a in A:
    if a >= 0:
        pos.append(a)
    else:
        neg.append(-a)
pos = sorted(pos)
neg = sorted(neg)
mod = 10**9+7
ans = 1
sign = 1
if K%2 == 1: #Kが奇数の時pos（ある場合）から必ず１つ取る
    if len(pos) > 0:
        ans = ans*pos.pop() % mod
    else:
        ans = ans*neg.pop(0) % mod
        sign *= -1
    K -= 1
while K > 0: #偶数の場合と奇数の残りの処理
    if len(pos) == 1 and len(neg) == 1:
        ans = ans*-neg.pop()*pos.pop() % mod
    elif sign == 1:#通常バージョン
        if len(pos) < 2 or (len(neg) >= 2 and pos[-2]*pos[-1] < neg[-2]*neg[-1]):
            ans = ans*neg.pop()*neg.pop() % mod
        else:
            ans = ans*pos.pop()*pos.pop() % mod
    else:#奇数の前処理で負になっている場合(最終結果も負になるので小さくしたい)
        if len(pos) < 2 or (len(neg) >= 2 and pos[-2]*pos[-1] < neg[-2]*neg[-1]):
            ans = ans*neg.pop(0)*neg.pop(0) % mod
        else:
            ans = ans*pos.pop(0)*pos.pop(0) % mod
    K -= 2
ans = ans*sign % mod
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
a.sort()
D = [[a[i+j-k] for j in range(k)] for i in range(n-1)]
A = (functools.reduce(operator.mul,D[_]) for _ in range(n-1))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
a.sort()
D = [[a[i+j-k] for j in range(k)] for i in range(n-1)]
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
import math
N,K=map(int,input().split())
A=list(map(int,input().split()))

A.sort()
S=sorted(A)

Min=[]

for i in A:
  if(i<0):
    Min.append(S.pop(0))
  else:
    break


S.sort(reverse=True)

#print(Min,S)

ans=int(1)

if( len(S)==0 and K%2==1 ):
  Min.sort(reverse=True)
  for i in Min[:K]:
    ans*=i

elif(N==K):
  for i in A:
    ans *= i

else:
  while(K>0):
    if(K==1):
      ans*=S.pop(0)
      K -=1
    elif(len(S)<=1):
      ans *= Min.pop(0)
      ans *= Min.pop(0)
      K -= 2
    elif(len(Min)<=1):
      ans *= S.pop(0)
      ans *= S.pop(0)
      K -=2
    elif(S[0]*S[1]<Min[0]*Min[1]):
      ans *= Min.pop(0)
      ans *= Min.pop(0)
      K -= 2
    else:
      ans *= S.pop(0)
      ans *= S.pop(0)
      K -=2

print(ans%(10**9+7))

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split(' '))
l = map(int, input().split(' '))

s = 1
if n == k:
	for i in l:
		s *= i
	print(s % 1000000007)
else:
	pos = []
	neg = []

	for i in l:
		if i >= 0:
			pos.append(i)
		else:
			neg.append(i)

	pos.sort()
	neg.sort(reverse=True)
	answer = []

	if k % 2 == 1 and not pos:
		for i in range(k):
			s *= neg[i]
		print(s % 1000000007)

	else:
		if k % 2 == 1:
			s = pos.pop()
		for i in range(k//2):
			if len(pos) >= 2:
				answer.append(pos.pop()*pos.pop())
			else:
				break
		for i in range(k//2):
			if len(neg) >= 2:
				answer.append(neg.pop()*neg.pop())
			else:
				break
		answer.sort(reverse=True)
		for i in range(k//2):
			s *= answer[i]
		print(s % 1000000007)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split(' '))
l = map(int, input().split(' '))

s = 1
if n == k:
	for i in l:
		s *= i
	print(s % 1000000007)
else:
	pos = []
	neg = []

	for i in l:
		if i >= 0:
			pos.append(i)
		else:
			neg.append(i)

	pos.sort()
	neg.sort(reverse=True)
	answer = []

	if k % 2 == 1 and not pos:
		for i in range(k):
			s *= neg[i]
		print(s % 1000000007)

	else:
		if k % 2 == 1:
			s = pos.pop()
		while len(pos) >= 2:
			answer.append(pos.pop()*pos.pop())
		while len(neg) >= 2:
			answer.append(neg.pop()*neg.pop())
		answer.sort(reverse=True)
		for i in range(k//2):
			s *= answer[i]
		print(s % 1000000007)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split(' '))
l = map(int, input().split(' '))

s = 1
if n == k:
	for i in l:
		s *= i
	print(s % 1000000007)
else:
	pos = []
	neg = []

	for i in l:
		if i >= 0:
			pos.append(i)
		else:
			neg.append(i)

	pos = sorted(pos)
	neg = sorted(neg)[::-1]
	answer = []
	s = 1

	if k % 2 == 1 and not pos:
		for i in neg[:k]:
			s *= i
		print(s % 1000000007)

	else:
		if k % 2 == 1:
			s = pos.pop()
		while len(pos) >= 2:
			answer.append(pos.pop()*pos.pop())
		while len(neg) >= 2:
			answer.append(neg.pop()*neg.pop())
		answer = sorted(answer)[::-1]
		for i in range(k//2):
			s *= answer[i]
		print(s % 1000000007)

Submission status: Time Limit Exceeded

Solution code:
import functools
import operator
import itertools
import heapq
n,k = map(int,input().split())
a = list(map(int,input().split()))
if n>=2*k:
  a_plus = heapq.nlargest(k, a)
  a_minus = heapq.nsmallest(k, a)
  a_new = a_plus+a_minus
  comb = itertools.combinations(a_new,k)
else:
  comb = itertools.combinations(a,k)

l = [list(_) for _ in comb]  
A = (functools.reduce(operator.mul,l[_]) for _ in range(len(l)))
 
l_max = max(A)
waru = 10**9 + 7
 
mod = l_max % waru
print(mod)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
a.sort()
D = [[a[i+j-k] for j in range(k)] for i in range(len(a))]
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
def main():
  
  import itertools
  import heapq
  import sys
  import functools
  import operator
  import numpy as np
  input = sys.stdin.readline
#-------------
  n,k = map(int,input().split())
  a = list(map(int,input().split()))
#-------------
  b = np.abs(a)
  b = sorted(a,reverse = True)
  b_k = b[k-1] 
  a_new = [a[_] for _ in range(len(a)) if np.abs(a)[_] >= b_k]
  a_new.sort()
  D = [[a_new[i+j-k] for j in range(k)] for i in range(len(a_new))]
  A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
  l_max = max(A)
  waru = 10**9 + 7
  print(l_max % waru)
main()

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
b = np.abs(a)
b1 = sorted(a,reverse = True)
b_k = b1[k-1] 
a_new = [a[_] for _ in range(len(a)) if b[_] >= b_k]
a_new.sort()
D = [[a_new[i+j-k] for j in range(k)] for i in range(len(a_new))]
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
b = np.abs(a)
b = sorted(a,reverse = True)
b_k = b[k-1] 
a_new = [a[_] for _ in range(len(a)) if np.abs(a)[_] >= b_k]
a_new.sort()
D = [[a_new[i+j-k] for j in range(k)] for i in range(len(a_new))]
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
b = np.abs(a)
b = sorted(a,reverse = True)
b_k = b[k-1] 
a_new = [a[_] for _ in range(len(a)) if np.abs(a)[_] >= b_k]
a_new.sort()
C=[]
D=[]
for i in range(len(a_new)):
  for j in range(k):
    C.append(a_new[i+j-k])
  D.append(C)
  C=[]    
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
b = np.abs(a)
b = sorted(a,reverse = True)
b_k = b[k-1] 
a_new = [a[_] for _ in range(len(a)) if np.abs(a)[_] >= b_k]
a_new.sort()
C=[]
D=[]
for i in range(len(a)):
  for j in range(k):
    C.append(a_new[i+j-k])
  D.append(C)
  C=[]    
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
b = np.abs(a)
b = sorted(a,reverse = True)
b_k = b[k-1] 
a_new = [a[_] for _ in range(len(a)) if np.abs(a)[_] >= b_k]
a_new.sort()
C=[]
D=[]
for i in range(len(a)):
  for j in range(k):
    C.append(a[i+j-k])
  D.append(C)
  C=[]    
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
a.sort()
C=[]
D=[]
for i in range(len(a)):
  for j in range(k):
    C.append(a[i+j-k])
  D.append(C)
  C=[]    
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
import math

n, k = map(int, input().split(' '))
l = map(int, input().split(' '))
pos = []
neg = []

for i in l:
	if i >= 0:
		pos.append(i)
	else:
		neg.append(i)

p = 0
n = 0
pos = sorted(pos)[::-1]
neg = sorted(neg)

answer = []
placeholder = -1

if k % 2 == 1:
	if len(pos) > 0:
		placeholder = pos.pop()
	else:
		placeholder = -2
		neg = neg[::-1]
	k -= 1

len_pos = len(pos)
len_neg = len(neg)
pos.append(0)
pos.append(0)
neg.append(0)
neg.append(0)

for i in range(k//2):
	if pos[p+0] * pos[p+1] >= neg[n+0] * neg[n+1]:
		answer.append(pos[p+0])
		answer.append(pos[p+1])
		p += 2
		p = min(p, len_pos)

	else:
		answer.append(neg[n+0])
		answer.append(neg[n+1])
		n += 2
		n = min(n, len_neg)

if placeholder == -2:
	answer.append(neg[n])
elif placeholder != -1:
	answer.append(max(placeholder, pos[p]))

s = 1
for i in answer:
	s *= i
print(s % 1000000007)

Submission status: Time Limit Exceeded

Solution code:
from functools import reduce

n, k = map(int, input().split())
a = list(map(int, input().split()))
MOD = 10**9+7
ps = [i for i in a if i >= 0]
ps.sort(reverse=True)
ms = [i for i in a if i < 0]
ms.sort()
res = 1
if n == k:
    res = reduce(lambda a, b: a*b, a, 1)
elif len(ps) == 0:
    if k % 2 != 0:
        ms.sort(reverse=True)
    res = reduce(lambda a, b: a*b, ms[:k], 1)
else:
    if k % 2 == 1:
        res *= ps[0]
        ps = ps[1:]
        k -= 1
    c_ms = []
    for i in range(0, len(ms)-1, 2):
        c_ms.append(ms[i]*ms[i+1])
    c_ps = []
    for i in range(0, len(ps)-1, 2):
        c_ps.append(ps[i]*ps[i+1])
    c_ms.extend(c_ps)
    c_ms.sort(reverse=True)
    res *= reduce(lambda a, b: a*b, c_ms[:k//2], 1)
print(res % MOD)

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations
N,K=map(int,input().split())
arr=list(map(int,input().split()))
ans=[]


for i in combinations(arr,K):
    kari=1
    for j in range(K):
        kari*=i[j]
    ans.append(kari)

print(max(ans)%(10**9+7))

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
# import bisect
# import numpy as np
# from collections import deque
from collections import deque
# map(int, sys.stdin.read().split())
import itertools
import heapq


def input():
    return sys.stdin.readline().rstrip()


def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    mod = 10 ** 9 + 7
    A.sort()
    A = deque(A)
    #    print(A)
    A_minus = deque([s for s in A if s < 0])
    A_plus = deque([s for s in A if s >= 0])

    #    print(A_plus)
    #    print(A_minus)
    AA = []
    if N == K:
        ans = 1
        for l in range(N):
            ans *= A[l] 
            ans %=mod
        print(ans % mod)

    elif K % 2 == 0:
        while len(A_minus) >= 2:
            a1 = A_minus.popleft()
            a2 = A_minus.popleft()
            AA.append(-a1 * a2)

        while len(A_plus) >= 2:
            a1 = A_plus.pop()
            a2 = A_plus.pop()
            AA.append(-a1 * a2)
        ans = 1
        heapq.heapify(AA)
        for i in range(K // 2):
            ans *= (-1 * heapq.heappop(AA)) % mod
        print(ans % mod)

    elif len(A_plus) == 0:
        ans = 1
        for i in range(K):
            ans *= A_minus.pop() % mod
        print(ans % mod)

    else:
        ans = A_plus.pop()
        while len(A_minus) >= 2:
            a1 = A_minus.popleft()
            a2 = A_minus.popleft()
            AA.append(-a1 * a2)

        while len(A_plus) >= 2:
            a1 = A_plus.pop()
            a2 = A_plus.pop()
            AA.append(-a1 * a2)

        heapq.heapify(AA)
        for i in range(K // 2):
            ans *= (-1 * heapq.heappop(AA)) % mod
        print(ans % mod)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

# import bisect
# import numpy as np
# from collections import deque
from collections import deque
# map(int, sys.stdin.read().split())
# import heapq
import bisect


# def input():
#     return sys.stdin.readline().rstrip()


def main():
    N, K = map(int, input().split())
    A = sorted(list(map(int, input().split())))
    mod = 10 ** 9 + 7

    #    print(A)
    #    print(A_plus)
    #    print(A_minus)
    if N == K:
        ans = 1
        for i in range(K):
            ans *= A[i] % mod
        print(ans % mod)

    elif A[-1] < 0:
        ans = 1
        for i in range(K):
            ans *= A[-(i + 1)] % mod
        print(ans % mod)

    elif K % 2 == 0:
        ans = 1
        j = 0
        i = N - 1
        for _ in range(K // 2):
            if A[j] * A[j + 1] > A[i] * A[i - 1]:
                ans *= A[j] * A[j + 1]
                ans %= mod
                j += 2
            else:
                ans *= A[i] * A[i - 1]
                ans %= mod
                i -= 2
        print(ans % mod)

    else:
        ans = A[-1]
        j = 0
        i = N - 2
        for _ in range(K // 2):
            if A[j] * A[j + 1] > A[i] * A[i - 1]:
                ans *= A[j] * A[j + 1]
                ans %= mod
                j += 2
            else:
                ans *= A[i] * A[i - 1]
                ans %= mod
                i -= 2
        print(ans % mod)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
b = np.abs(a)
b = sorted(a,reverse = True)
b_k = b[k-1] 
a_new = [a[_] for _ in range(len(a)) if np.abs(a)[_] >= b_k]
 
comb = itertools.combinations(a_new,k)  
l = [list(_) for _ in comb]  
A = (functools.reduce(operator.mul,l[_]) for _ in range(len(l)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
b = np.abs(a)
b = sorted(a,reverse = True)
b_k = b[k-1] 
a_new = [a[i] for i in range(len(a)) if np.abs(a)[i] >= b_k]
 
comb = itertools.combinations(a_new,k)  
l = [list(_) for _ in comb]  
A = (functools.reduce(operator.mul,l[_]) for _ in range(len(l)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
A = sorted(list(map(int, input().split())))
mod = 10 ** 9 + 7

#    print(A)
#    print(A_plus)
#    print(A_minus)
if N == K:
    ans = 1
    for i in A:
        ans *= i % mod
    print(ans % mod)

elif A[-1] < 0:
    ans = 1
    for i in range(K):
        ans *= A[-(i + 1)] % mod
    print(ans % mod)

elif K % 2 == 0:
    ans = 1
    j = 0
    i = N - 1
    for _ in range(K // 2):
        if A[j] * A[j + 1] > A[i] * A[i - 1]:
            ans *= A[j] * A[j + 1]
            ans %= mod
            j += 2
        else:
            ans *= A[i] * A[i - 1]
            ans %= mod
            i -= 2
    print(ans % mod)

else:
    ans = A[-1]
    j = 0
    i = N - 2
    for _ in range(K // 2):
        if A[j] * A[j + 1] > A[i] * A[i - 1]:
            ans *= A[j] * A[j + 1]
            ans %= mod
            j += 2
        else:
            ans *= A[i] * A[i - 1]
            ans %= mod
            i -= 2
    print(ans % mod)