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: Runtime Error

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N, K = MAP()
A = LIST()

a = []
for x in A:
	flg = 0
	if x < 0:
		flg = 1
	a.append([x, abs(x), flg])

a.sort(key = lambda x: -x[1])

#print(a)

flg_sum = sum([x[2] for x in a[:K]])

if flg_sum%2 == 0:
	ans = 1
	for x in a[:K]:
		ans = ans*x[1]%mod
	print(ans)
	exit()


flg = a[K-1][2]
for i in range(K, N):
	if a[i][2] != flg:
		ans = 1
		for j in range(K-1):
			ans = ans*a[j][1]%mod
		print(ans*a[i][1]%mod)
		exit()

for i in range(K-1, -1, -1):
	if a[i][2] != flg:
		ans = 1
		for j in range(K+1):
			if j != i:
				ans = ans*a[j][1]%mod
		print(ans)
		exit()

ans = 1
for x in a[::-1][:K]:
	ans = ans*x[0]%mod

print(ans)

Submission status: Runtime Error

Solution code:
from bisect import bisect_right, bisect_left


def mod_pow(a, n):
    res = 1
    while n > 0:
        if n & 1:
            res = res * a % mod
        a = a * a % mod
        n >>= 1
    return res


n, k = map(int, input().split())
a = list(map(int, input().split()))
l_1 = sorted(a, key=lambda x: abs(x), reverse=True)
l_2 = sorted(a)

mod = 10 ** 9 + 7

if n == k:
    res = 1
    for v in a:
        res = res * v % mod
elif l_2[-1] < 0:
    res = 1
    if k % 2 == 0:
        for v in l_2[:k]:
            res = res * v % mod
    else:
        for v in l_2[n-1:n-k-1:-1]:
            res = res * v % mod
else:
    cnt = 0
    for v in l_1[:k]:
        if v < 0:
            cnt += 1

    res = 1
    for v in l_1[:k]:
        res = res * abs(v) % mod

    if cnt % 2 == 1:
        if l_1[k-1] > 0:
            pos_1 = bisect_right(l_2, -l_1[k-1]) - 1
            pos_2 = bisect_left(l_2, l_1[k-1])
        else:
            pos_1 = bisect_right(l_2, l_1[k-1]) - 1
            pos_2 = bisect_left(l_2, -l_1[k-1])
        
        if l_2[pos_1+1] >= 0:
            res = (res * mod_pow(-l_2[pos_1], mod-2) % mod) * l_2[pos_2-1] % mod
        elif l_2[pos_2-1] <= 0:
            res = (res * mod_pow(l_2[pos_2], mod-2) % mod) * l_2[pos_1+1] % mod
        else:
            if l_2[pos_1] * l_2[pos_1+1] > l_2[pos_2] * l_2[pos_2-1]:
                res = (res * mod_pow(l_2[pos_2], mod-2) % mod) * l_2[pos_1+1] % mod
            else:
                res = (res * mod_pow(-l_2[pos_1], mod-2) % mod) * l_2[pos_2-1] % mod

print(res)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
mod=10**9+7
A=list(map(int,input().split()))
A.sort(reverse=True)
Plus=[]
Minus=[]
Zero=[]
for i in range(N):
    if A[i]>0:
        Plus.append(A[i])
    elif A[i]<0:
        Minus.append(-A[i])
    else:
        Zero.append(A[i])
Plus.sort(reverse=True)
Minus.sort(reverse=True)
if K==N:
    ans=1
    for i in range(K):
        ans=ans*A[i]
        ans%=mod
    print(ans)
    exit()
if len(Plus)==0:
    if len(Zero)==0:
        if K%2==0:
            ans=1
            for i in range(K):
                ans=ans*Minus[i]
                ans%=mod
            print(ans)
        else:
            ans=1
            for i in range(K):
                ans=ans*Minus[-i-1]
                ans%=mod
            print((-ans)%mod)
    else:
        if len(Minus)>=K:
            if K%2==0:
                ans=1
                for i in range(K):
                    ans=ans*Minus[i]
                    ans%=mod
                print(ans)
            else:
                print(0)
        else:
            print(0)
    exit()
if len(Minus)==0:
    ans=1
    for i in range(K):
        ans=ans*A[i]
        ans%=mod
    print(ans)
    exit()
if len(Zero)>N-K:
    print(0)
    exit()
if len(Zero)+K==N:
    if len(Minus)%2==0:
        ans=1
        for i in range(N):
            if A[i]!=0:
                ans=ans*abs(A[i])
                ans%=mod
        print(ans)
    else:
        print(0)
    exit()
n=len(Plus)
m=len(Minus)
'''
+:x0,...,x(n-1)
-:y0,...,y(m-1)

x0*...x(K-l-1)*y0*...y(l-1)
yl*y(l+1)/x(K-l-1)*x(K-l-2)
これはlについて単調減少
<1となるはじめてのタイミングでbreak
'''
l=K-n
if l%2==1:
    l+=1
x=l
while(l<=m and l<=K):
    if (l+2)<=min(m,K):
        if Minus[l]*Minus[l+1]>=Plus[K-l-1]*Plus[K-l-2]:
            x=l+2
    l+=2
ans=1
for i in range(x):
    ans=ans*Minus[i]
    ans%=mod
for i in range(K-x):
    ans=ans*Plus[i]
    ans%=mod
print(ans)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np

mod = int(10e8+7)

n, k = map(int, input().split())
a = np.array(list(map(int, input().split())))

a_ = np.abs(a)
isN = (a!=a_).astype(int)

a = a[np.argsort(a_)[::-1]]
isN = isN[np.argsort(a_)[::-1]]
a_ = np.sort(a_)[::-1]

numN = np.sum(isN)
numP = n-numN

if k==1:
    k = isP
    print(np.max(a))
    sys.exit()

if np.sum(isN[:k])%2==0:
    ans = 1
    for i in range(k):
        ans *= a_[i]
        ans %= mod
    print(int(ans))
    sys.exit()

if not numP:
    ans = 1
    for i in range(1, k+1)[::-1]:
        ans *= -a_[-i]
        ans %= mod

    print(int(ans))
    sys.exit()

maxN = 0
maxP = 0

for i in range(k, n):
    if isN[i]:
        maxN = i
        break

for i in range(k, n):
    if not isN[i]:
        maxP = i
        break

minN = n
minP = n

for i in range(k)[::-1]:
    if isN[i]:
        minN = i
        break

for i in range(k)[::-1]:
    if not isN[i]:
        minP = i
        break

ans_1 = 1

for i in range(k):
    if i == minP:
        if maxN:
            ans_1 *= a_[maxN]
            ans_1 %= mod
        continue

    ans_1 *= a_[i]
    ans_1 %= mod

ans_2 = 1

for i in range(k):
    if i == minN:
        if maxP:
            ans_2 *= a_[maxP]
            ans_2 %= mod
        continue

    ans_2 *= a_[i]
    ans_2 %= mod

print(int(max(ans_1, ans_2)))

Submission status: Runtime Error

Solution code:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy
import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]

######################################################################################################
def zenkake(K):
    num=1
    for a in K:
        num*=(mod+a)
        num%=mod
    return num
n,k=inputintlist()
A=inputintlist()
A.sort()


ans=-inf
#負の数を偶数個選ぶ
S=[]
F=[]
for a in A:
    if a<0:
        F.append(a)
    else:
        S.append(a)
S.reverse()
S.append(-1)
F.append(1)
fcnt=0
scnt=0
i=0
j=0
kakeru=[]
for a in range(k):
    if -F[i]<S[j]:
        kakeru.append(S[j])
        j+=1
        scnt+=1
    else:
        kakeru.append(F[i])
        i+=1
        fcnt+=1
S.pop()
F.pop()
if fcnt%2==0:
    ans=max(ans,zenkake(kakeru))
else:
    if len(S)>0:
        if fcnt==len(F) and scnt==len(S):
            pass
        elif fcnt==len(F):
            kakeru.append(S[scnt])
            kakeru[kakeru.index(F[fcnt-1])]=1
            ans=max(ans,zenkake(kakeru))
        elif scnt==len(S):
            kakeru.append(F[fcnt])
            kakeru[kakeru.index(S[scnt-1])]=1
            ans=max(ans,zenkake(kakeru))
        else:
            if -F[fcnt]<S[scnt]:
                kakeru.append(S[scnt])
                kakeru[kakeru.index(F[fcnt-1])]=1
            else:
                kakeru.append(F[fcnt])
                kakeru[kakeru.index(S[scnt-1])]=1
            ans=max(ans,zenkake(kakeru))
if ans==-inf:
    #負の数を奇数個
    S=[]
    F=[]
    for a in A:
        if a<0:
            F.append(a)
        else:
            S.append(a)
    S.reverse()
    F.reverse()
    if len(S)>=k:
        ans=max(ans,zenkake(S[:k]))
    else:
        num=zenkake(S[:k])
        k-=len(S)
        if k%2==1:
            for a in range(k):
                num*=F[a]
                num%=mod
        ans=max(ans,num)
print(ans)

Submission status: Runtime Error

Solution code:
n , k = map(int, input().split())
a = list(map(int, input().split()))
neg = []
pos = []
mod = 10**9+7
for i in range(n):
    if a[i] >= 0:
        pos.append(a[i])
    else:
        neg.append(a[i])
neg.sort()
pos.sort(reverse = True)
min_num = -1
good_num = -1
if k % 2 == 1 and len(pos) == 0:
    ans = 1
    neg.sort(reverse = True)
    for i in range(k):
        ans *= neg[i]
        ans %= mod
    print(ans)
else:
    #最大化するとき
    for i in range(0,k+1,2):
        #i個だけnegから取る。
        if i > len(neg) or k - i > len(pos):
            continue
        m = 0
        if i >= 0:
            m = abs(neg[i-1])
        if k-i-1 >= 0:
            m = min(m, pos[k-i-1])
        if m > min_num:
            min_num = m
            good_num = i
    ans = 1
    for i in range(good_num):
        ans *= neg[i]
        ans %= mod
    for i in range(k - good_num):
        ans *= pos[i]
        ans %= mod
    print(ans % mod)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
po = sorted([ai for ai in a if ai > 0], reverse=True)
ne = sorted(ai for ai in a if ai < 0)
ze = 0 in a
mod = 10**9 + 7
c = 1
if len(po) == 0 or len(po) + len(ne) // 2 * 2 < k:
    if ze:
        print(0)
    else:
        for bi in sorted(po + ne, key=abs)[:k]:
            c = c * bi % mod
        print(c)
elif len(ne) == 0:
    for ai in sorted(a, reverse=True):
        c = c * ai % mod
    print(c)
else:
    if len(po) >= k:
        pi = k - 1
        ni = -1
        pc = po[:k]
        nc = []
    else:
        if (k - len(po)) % 2:
            pi = len(po) - 2
            pc = po[:-1]
        else:
            pi = len(po) - 1
            pc = po
        ni = k - len(pc) - 1
        nc = ne[:k - len(pc)]
    for _ in range(len(pc) // 2):
        if ne[ni + 1] * ne[ni + 2] < po[pi - 1] * po[pi - 2]:
            break
        nc = nc + ne[ni + 1:ni + 3]
        pc = pc [:-2]
        ni += 2
        pi -= 2
    for pp in pc:
        c = c * pp % mod
    for nn in nc:
        c = c * nn % mod
    print(c)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))

a.sort(reverse=True, key=lambda x:abs(x))
cnt = 0
im = 0
ip = 0
cp = 0
mod = 10 ** 9 + 7

for i, ai in enumerate(a):
    if i < k:
        if ai < 0:
            im = i
            cnt += 1
        if ai > 0:
            ip = i
    if ai > 0:
        cp += 1

ans = 1
f = 0

# print(a)
if cnt % 2:
    if cp == 0:
        a.sort(reverse=True)
        for i, ai in enumerate(a):
            if i == k:
                break
            ans *= ai
            ans %= mod
        print(ans)
    else:
        ans = 1
        cnt = 0
        f = 0
        for i, ai in enumerate(a):
            if cnt == k:
                f = 2
                break
            if i == im:
                f = 1
                continue
            if f == 1 and ai <= 0:
                continue
            ans *= abs(ai)
            ans %= mod
            # print(i, ai)
            cnt += 1
        if f == 2:
            print(ans)
        else:
            ans = 1
            cnt = 0
            f = 0
            for i, ai in enumerate(a):
                if cnt == k:
                    f = 2
                    break
                if i == ip:
                    f = 1
                    continue
                if f == 1 and ai >= 0:
                    continue
                ans *= abs(ai)
                ans %= mod
                # print(i, ai)
                cnt += 1
            if f == 2:
                print(ans)
            else:
                ans = 1
                a.sort(reverse=True)
                for i, ai in enumerate(a):
                    if i == k:
                        break
                    ans *= ai
                    ans %= mod
                print(1/0)
                print(ans)

else:
    for i, ai in enumerate(a):
        if i == k:
            break
        ans *= abs(ai)
        ans %= mod
    print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np

N,K = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(abs, A))

A = sorted(A)
A = np.array(A)
A = A % (10**9+7)

dp = [0 for i in range(N//4+1)]

for i in range(N//4+1):
  if i == 0:
    a = A[-K:]
    prod = 1
    for j in range(len(a)):
      prod *= a[i]
      prod = prod % (10**9+7)
    dp[0] = prod
  else:
    if -K+i*2 < 0:
      a = np.hstack([A[:i*2], A[-K+i*2:]])
      prod = 1
      for j in range(len(a)):
        prod *= a[i]
        prod = prod % (10**9+7)
      dp[i] = prod
    else:
      a = A[:i*2]
      prod = 1
      for j in range(len(a)):
        prod *= a[i]
        prod = prod % (10**9+7)
      dp[i] = prod

print(max(dp))

Submission status: Runtime Error

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    N, K = [int(x) for x in input().strip().split()]
    A = sorted([int(x) for x in input().strip().split()])
    zeros = A.count(0)
    max_A = max(A)
    mod = 10 ** 9 + 7
    if N == K:
        ans = 1
        for k in range(K):
            ans = (ans * A[k]) % mod
        print(ans)
        return
    if max_A < 0:
        if K % 2:
            ans = 1
            for k in range(K):
                ans = (ans * A[-1-k]) % mod
            print(ans)
            return
        else:
            for k in range(K):
                ans = (ans * A[k]) % mod
            print(ans)
            return
    elif max_A == 0:
        if A[-K] == 0:
            print(0)
            return
        else:
            if K % 2:
                print(0)
                return
            else:
                for k in range(K):
                    ans = (ans * A[k]) % mod
                print(ans)
                return
    else:
        if N - zeros < K:
            print(0)
            return
        if N - zeros == K:
            if len([a for a in A if a < 0]) % 2:
                print(0)
                return
            else:
                ans = 1
                for a in A:
                    if a != 0:
                        ans = (ans * a) % mod
                print(ans)
                return
        ans = 1
        A.sort(key=lambda x: abs(x), reverse=True)
        minus = 0
        for k in range(K):
            if A[k] < 0:
                minus += 1
                minus_last_index = k
            ans = (ans * A[k]) % mod
        if minus % 2:
            for k in range(minus_last_index):
                ans = (ans * A[k]) % mod
            k = minus_last_index + 2
            k2 = k
            while k2 < K:
                if A[k] >= 0:
                    ans = (ans * A[k]) % mod
                    k += 1
                    K2 = k
                else:
                    k += 1

        print(ans)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n = [int(i) for i in input().split()]

plus = list()
minus = list()
for i in input().split():
  if int(i) > 0:
    plus.append(int(i))
  else:
    minus.append(int(i))
    
plus.sort()
minus.sort(reverse=True)
ans = 1
k = n[1]
while k != 0:
  if k == 1:
    ans *= plus[0]
    k = 0
  if len(minus) < 2:
    ans *= plus[0]*plus[1]
    del plus[0]
    del plus[0]
  elif plus[0]*plus[1] < minus[0]*minus[1]:
    ans *= minus[0]*minus[1]
    del minus[0]
    del minus[0]
  else:
    ans *= plus[0]*plus[1]
    del plus[0]
    del plus[0]
  k -= 2
print(ans%(10**9 + 7))

Submission status: Runtime Error

Solution code:
import itertools
N, K = map(int, input().split())
A = list(map(int, input().split()))
ans = -9999999999
for x in itertools.combinations(A, K):
    seki = 1
    print(x)
    for i in range(len(x)):
        seki *= x[i]
    ans = max(ans, seki)

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

Submission status: Runtime Error

Solution code:
import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter
# a.sort(key=itemgetter(i)) # i番目要素でsort
from functools import lru_cache
# @lru_cache(maxsize=None)
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9 + 7
eps = 10**-7


def inp():
    '''
    一つの整数
    '''
    return int(input())


def inpl():
    '''
    一行に複数の整数
    '''
    return list(map(int, input().split()))


def str_inp():
    '''
    文字列をリストとして読み込む
    '''
    return list(input()[:-1])


n, k = inpl()
a = inpl()
data = [[abs(i), i < 0] for i in a]
all_minus = 0
for t in data:
    if t[1]:
        all_minus += 1
print(0/0)
if all_minus == n:
    ans = 1
    data.sort()
    for i in range(k):
        ans = ans * data[i][0] % mod
    print(-ans % mod)
    exit()
data.sort(reverse=True)
last_minus = 0
last_plus = 0
ans = 1
minus_amount = 0
for i in range(k):
    elem, sign = data[i][0], data[i][1]
    if elem == 0:
        print(0)
        exit()
    ans = ans * elem % mod
    minus_amount += sign
    if sign:
        last_minus = elem
    else:
        last_plus = elem
if minus_amount % 2 == 0:
    print(ans%mod)
    exit()
if n==k:
    print(-ans % mod)
    exit()
tmp_plus = 0
tmp_minus = 0
for i in range(k, n):
    elem, sign = data[i][0], data[i][1]
    if last_plus and sign and not tmp_minus:
        tmp_minus = elem
    elif last_minus and not sign and not tmp_plus:
        tmp_plus = elem
if tmp_plus == 0 and tmp_minus == 0:
    ans = 0
elif last_plus == 0:
    ans = ans * pow(last_minus, mod - 2, mod) * tmp_plus % mod
elif last_minus == 0:
    ans = ans * pow(last_plus, mod - 2, mod) * tmp_minus % mod
elif tmp_plus * last_plus > tmp_minus * last_minus:
    ans = ans * pow(last_minus, mod - 2, mod) * tmp_plus % mod
else:
    ans = ans * pow(last_plus, mod - 2, mod) * tmp_minus % mod
print(ans)

Submission status: Runtime Error

Solution code:
mod = 10**9+7

import sys
input = sys.stdin.buffer.readline

def main():

    n, k = map(int, input().split())
    A = list(map(int, input().split()))
    P = []
    N = []

    for a in A:
        if a >= 0:
            P.append(a)
        else:
            N.append(a)
    P.sort(reverse=True)
    N.sort()
    #print(P)
    #print(N)

    if len(P) == 0:
        if k%2 == 0:
            N.sort()
            ans = 1
            for i in range(k):
                ans *= N[i]
                ans %= mod
        else:
            N.sort(reverse=True)
            ans = 1
            for i in range(k):
                ans *= N[i]
                ans %= mod
        print(ans)
        exit()

    if len(P) == 1:
        if k%2 == 0:
            N.sort()
            ans = 1
            for i in range(k):
                ans *= N[i]
                ans %= mod
        else:
            ans = P[0]
            N.sort(reverse=True)
            for i in range(k-1):
                ans *= N[i]
                ans %= mod
        print(ans)
        exit()


    if len(N) == 0:
        ans = 1
        for i in range(k):
            ans *= P[i]
            ans %= mod
        print(ans)
        exit()

    if len(N) == 1:
        if len(P) >= k:
            ans = 1
            for i in range(k):
                ans *= P[i]
                ans %= mod
            print(ans)
            exit()
        else:
            print(N[0])
            exit()

    import heapq
    if k%2 == 0:
        P_ = []
        N_ = []
        if len(P) != 1:
            for i in range(len(P)):
                if i%2 == 1:
                    continue
                P_.append(-P[i]*P[i+1])
            for i in range(len(N)):
                if i%2 == 1:
                    continue
                N_.append(-N[i]*N[i+1])
            heapq.heapify(P_)
            heapq.heapify(N_)
            q = k//2
            ans = 1
            for i in range(q):
                if P_:
                    x = heapq.heappop(P_)*(-1)
                else:
                    x = -1
                if N_:
                    y = heapq.heappop(N_)*(-1)
                else:
                    y = -1
                if x >= y:
                    ans *= x
                    ans %= mod
                    if y >= 0:
                        heapq.heappush(N_, y*(-1))
                else:
                    ans *= y
                    ans %= mod
                    if x >= 0:
                        heapq.heappush(P_, x*(-1))
        else:
            ans = 1
            for i in range(k):
                ans *= N[i]
                ans %= mod
    else:
        p = P[0]
        P = P[1:]
        P_ = []
        N_ = []
        if len(P) != 1:
            for i in range(len(P)):
                if i%2 == 1:
                    continue
                P_.append(-P[i]*P[i+1])
            for i in range(len(N)):
                if i%2 == 1:
                    continue
                N_.append(-N[i]*N[i+1])
            heapq.heapify(P_)
            heapq.heapify(N_)
            q = k//2
            ans = p
            for i in range(q):
                if P_:
                    x = heapq.heappop(P_)*(-1)
                else:
                    x = -1
                if N_:
                    y = heapq.heappop(N_)*(-1)
                else:
                    y = -1
                if x >= y:
                    ans *= x
                    ans %= mod
                    if y >= 0:
                        heapq.heappush(N_, y*(-1))
                else:
                    ans *= y
                    ans %= mod
                    if x >= 0:
                        heapq.heappush(P_, x*(-1))
        else:
            ans = p
            for i in range(k):
                ans *= N[i]
                ans %= mod
    print(ans)

if __name__ == '__main__':
    main()