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: Wrong Answer

Solution code:
N, K = map(int, input().split())
mod = 10**9 + 7
plus = []
minus = []
zlen = 0
for i in map(int, input().split()):
    if i >= 0:
        plus.append(i)
    elif i < 0:
        minus.append(i)
    else:
        zlen += 1
plen = len(plus)
mlen = len(minus)
# if K > plen + mlen:
#     print(0)
#     import sys
#     sys.exit()
plus.sort(reverse=True)
minus.sort()
pp = [1]
mp = [1]
for p in plus:
    pp.append((pp[-1]*p)%mod)
for m in minus:
    mp.append((mp[-1]*(-m))%mod)
ppm = [1]
mpm = [1]
for p in plus[::-1]:
    ppm.append((ppm[-1]*p)%mod)
for m in minus[::-1]:
    mpm.append((mpm[-1]*(-m))%mod)
ans = -float("inf")
ans_m = float("inf")
# kこマイナスから選ぶ
for k in range(K+1):
    if mlen < k:
        continue
    if plen < K-k:
        continue
    # 最大を目指す
    if k % 2 == 0:
        tmp = mp[k] * pp[K-k]
        ans = max(ans, tmp)
    # 絶対値最小を目指す
    else:
        tmp = mpm[k] * ppm[K-k]
        ans = min(ans, tmp)
# if ans == -float("inf"):
#     ans = -ans_m
# if ans < 0 and zlen > 0:
#     print(0)
#     import sys
#     sys.exit()
print(ans%mod)

Submission status: Wrong Answer

Solution code:
import sys
import itertools
def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))
def RN(N): return [input().strip() for i in range(N)]


def main():
    N, K = MI()
    A = LI()
    q = (10**9)+7
    ans = 0


    for i in itertools.combinations(A,K):
        i = list(i)
        seki = 1
        for j in i:
            seki = (seki*j)
        seki=seki%q
        if seki>ans:
            ans = seki

    print(ans)

    

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
from collections import deque
# N = int(input())
N, K = [int(_) for _ in input().split()]
A = [int(_) for _ in input().split()]
MOD = 10 ** 9 + 7
A_p = []
A_n = []
for a in A:
  if a >= 0:
    A_p.append(a)
  else:
    A_n.append(-a)

A_p.sort(reverse=True)
A_n.sort(reverse=True)
A_p = deque(A_p)
A_n = deque(A_n)

p_top = 0
n_top = 0
ans_p = deque([])
ans_n = deque([])
for i in range(K):
  if len(A_p) == 0:
    ans_n.append(A_n.popleft())
  elif len(A_n) == 0:
    ans_p.append(A_p.popleft())
  elif A_p[0] >= A_n[0]:
    ans_p.append(A_p.popleft())
  else:
    ans_n.append(A_n.popleft())
if len(ans_n) % 2 == 1:
  if len(ans_p) == 0 and len(A_p) > 0:
    ans_n.pop()
    ans_p.append(A_p.popleft())
  elif len(ans_n) == 0 and len(A_n) > 0:
    ans_p.pop()
    ans_n.append(A_n.popleft())
  elif len(ans_p) > 0 and len(ans_n) > 0 and ans_p[-1] >= ans_n[-1] and len(A_p) > 0:
    ans_n.pop()
    ans_p.append(A_p.popleft())
  elif len(ans_p) > 0 and len(ans_n) > 0 and ans_p[-1] < ans_n[-1] and len(A_n) > 0:
    ans_p.pop()
    ans_n.append(A_n.popleft())
ans = 1
for a in ans_p:
  ans = (a * ans) % MOD
for a in ans_n:
  ans = (a * ans) % MOD
if ans < 0:
  ans = 1
  A = [a for a in A if a < 0]
  A.sort(reverse=True)
  for i in range(K):
    ans = (ans * A[i]) % MOD
print(ans)

Submission status: Wrong Answer

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

l_pos=[]
l_neg=[]
for i in range(n):
  if l[i]<0:
    l_neg.append(l[i])
  else:
    l_pos.append(l[i])

l_neg.sort()
l_pos.sort()
a=len(l_neg)
b=len(l_pos)
a=a-1
b=b-1

if len(l_neg)==0:
  ans=1
  for i in range(k):
    ans*=l_pos[-1-i]
    ans=ans%mod

elif len(l_pos)==0:
  ans=1
  for j in range(k):
    ans*=l_neg[i]
    ans=ans%mod

elif k==n:
  ans=1
  for i in range(n):
    ans*=l[i]
    ans=ans%mod

else:
  ans=1
  cntodd=0
  while a>0 and b>0:
    if l_pos[b]>=abs(l_neg[a]):
      ans*=l_pos[b]
      ans=ans%mod
      b-=1
    
    elif l_pos[b]<abs(l_neg[a]):
      ans*=l_pos[b]
      ans=ans%mod
      a-=1
      cntodd+=1
    k-=1
    if k==1:
      break

  if cntodd%2==0 and k==1:
    ans*=l_pos[b]
    k-=1
  elif cntodd%2!=0 and k==1:
    if a+1<len(l_neg):
      a+=1
    ans=ans//l_neg[a]
    ans*=l_pos[b]
    k-=1
  if k>0:
    while b>0:
      ans*=l_pos[b]
      b-=1
      k-=1
      if k==0:
        break
        
        
  
  
 
print(ans%mod)

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

N,K = LI()
A = LI()

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)

for i in range(1,len(plus)):
    plus[i] = plus[i-1]*plus[i] % mod

for i in range(1,len(minus)):
    minus[i] = minus[i-1]*minus[i] % mod

plus = [1]+plus
minus = [1]+minus

ans = 0 if len(zero) else -float('inf')
for i in range(K+1):
    if i < len(plus) and K-i < len(minus):
        temp = plus[i]*minus[K-i]*(-1)**((K-i)%2)
        if temp > 0 and temp > ans:
            ans = temp



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()
minus.sort()

for i in range(1,len(plus)):
    plus[i] = plus[i-1]*plus[i]

for i in range(1,len(minus)):
    minus[i] = minus[i-1]*minus[i]

plus = [1]+plus
minus = [1]+minus

for i in range(K+1):
    if i < len(plus) and K-i < len(minus):
        temp = plus[i]*minus[K-i]*(-1)**((K-i)%2)
        if temp < 0 and temp > ans:
            ans = temp

print(ans%mod)

Submission status: Wrong Answer

Solution code:
from queue import PriorityQueue
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
# sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


mod = 10**9+7


def prod(l):
    ret = 1
    for e in l:
        e %= mod
        ret = (ret*e) % mod

    return ret


def main():
    n, k = geta(int)
    a = list(geta(int))

    p, n, z = [], [], 0
    for ai in a:
        if ai > 0:
            p.append(ai)
        elif ai < 0:
            n.append(-ai)
        else:
            z += 1

    ans = 1
    p.sort()
    n.sort()
    if k & 1 == 1:
        if len(p) == 0:
            if z > 0:
                print(0)
                exit()
            else:
                print(-prod(n[0:k]) % mod)
                exit()
        else:
            k -= 1
            ans = p.pop() % mod

    if len(p) + len(n) < k:
        print(0)
        exit()

    if len(n) & 1 == 1 and (len(p) + len(n) == k):
        if z > 0:
            print(0)
            exit()
        else:
            print(prod(p) * prod(n) % mod)
            exit()


    q = []

    n = n[::-1]
    for i in range(len(n)//2):
        q.append(n[2*i]*n[2*i+1])

    p = p[::-1]
    for i in range(len(p)//2):
        q.append(p[2*i]*p[2*i+1])

    q.sort(reverse=True)

    ans = ans * (prod(q[:k//2])) % mod

    print(ans % mod)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

N,K = map(int,S().split())
A = LI()
mod = 10**9+7

if N == 2 and K == 1:
    M = max(A)
    print(M % mod)
    exit()

a = 0  # 0の個数
b = 0
c = 0
B = []
C = []
D = []
for i in range(N):
    if A[i] == 0:
        a += 1
    elif A[i] > 0:
        b += 1
        B.append(A[i])
        D.append(A[i])
    else:
        c += 1
        C.append(A[i])
        D.append(A[i])
if N-a < K:
    print(0)
    exit()

ans = 1

if c == N and K % 2 == 1:
    C = sorted(C,reverse=True)
    for i in range(K):
        ans *= C[i]
        ans %= mod
    print(ans)
    exit()
if K == N:
    for i in range(N):
        ans *= A[i]
        ans %= mod
    print(ans)
    exit()
if b == 0 and K % 2 == 1 and a > 0:
    print(0)
    exit()

d = b + c
E = [(abs(A[i]),A[i]) for i in range(N)]
E = sorted(E,reverse=True)

if K == 1:
    print(max(A) % mod)
    exit()
if K == 2:
    if N == 3:
        M = max([E[0][1]*E[1][1],E[0][1]*E[2][1],E[1][1]*E[2][1]])
        print(M % mod)
        exit()
    else:
        M = max([E[0][1] * E[1][1], E[0][1] * E[2][1], E[1][1] * E[2][1],E[0][1] * E[3][1],E[1][1] * E[3][1],E[2][1] * E[3][1]])
        print(M % mod)
        exit()

r = 0
if K >= 3:
    for i in range(K-2):
        if E[i][1] < 0:
            r += 1
        ans *= E[i][0]
        ans %= mod

if K == N-1:
    x = E[K-2][1]
    y = E[K-1][1]
    z = E[K][1]
    a1 = x
    a1 *= y
    a2 = x
    a2 *= z
    a3 = y
    a3 *= z
    if r % 2 == 0:
        M = max([a1,a2,a3])
    else:
        M = min([a1,a2,a3])
    print((ans*M) % mod)
    exit()

else:
    x = E[K-2][1]
    y = E[K-1][1]
    z = E[K][1]
    w = E[K+1][1]
    a1 = x
    a1 *= y
    a2 = x
    a2 *= z
    a3 = y
    a3 *= z
    a4 = x
    a4 *= w
    a5 = y
    a5 *= w
    a6 = z
    a6 *= w
    if r % 2 == 0:
        M = max([a1,a2,a3,a4,a5,a6])
    else:
        M = min([a1,a2,a3,a4,a5,a6])
    print((ans*M) % mod)
    exit()

Submission status: Wrong Answer

Solution code:
#                          JAI SHREE RAM

import math; from collections import *
import sys; from functools import reduce

# sys.setrecursionlimit(10**6)
def get_ints(): return map(int, input().strip().split())
def get_list(): return list(get_ints())
def get_string(): return list(input().strip().split())
def printxsp(*args): return print(*args, end="")
def printsp(*args): return print(*args, end=" ")

UGLYMOD = int(1e9)+7; SEXYMOD = 998244353; MAXN = int(1e5)

# sys.stdin=open("input.txt","r");sys.stdout=open("output.txt","w")

# for _testcases_ in range(int(input())):
n, k = get_ints()
li = get_list()
pos = []
neg = []
ans = 1
zeroes = 0
for i in li:
    if i < 0: neg.append(i)
    elif i > 0: pos.append(i)
    else: zeroes += 1
lengthOfPos, lengthOfNeg = len(pos), len(neg)

if k&1 : #and (k - lengthOfPos) >= 0 and (k - lengthOfPos) & 1:
    if k > lengthOfPos:
        if zeroes:
            print("0")
        else:
            # last pr pakka negative ayega
            pos.extend([0] * zeroes)
            lengthOfPos, lengthOfNeg = len(pos), len(neg)
            pos.sort(); positionOfPos = 0
            neg.sort(reverse = True); positionOfNeg = 0
            while k > 1:
                try: negpower = neg[positionOfNeg] * neg[positionOfNeg+1]
                except: negpower = float('inf')
                try: pospower = pos[positionOfPos] * pos[positionOfPos+1]
                except: pospower = float('inf')
                if pospower <= negpower:
                    positionOfPos += 2
                    ans = (ans * (pospower % UGLYMOD)) % UGLYMOD
                else:
                    ans = (ans * (negpower % UGLYMOD)) % UGLYMOD
                    positionOfNeg += 2
                k -= 2
            if k == 1:
                try: negpower = neg[positionOfNeg]
                except: negpower = float('inf')
                try: pospower = pos[positionOfPos]
                except: pospower = float('inf')
                ans = (ans * min(pospower, negpower)) % UGLYMOD
            print(ans)
            
    else:
        pos.sort(reverse = True); positionOfPos = 0
        neg.sort(); positionOfNeg = 0
        ans = 1
        while k > 1:
            try: negpower = neg[positionOfNeg] * neg[positionOfNeg+1]
            except: negpower = -float('inf')
            try: pospower = pos[positionOfPos] * pos[positionOfPos+1]
            except: pospower = -float('inf')
            if pospower >= negpower:
                positionOfPos += 2
                ans = (ans * (pospower % UGLYMOD)) % UGLYMOD
            else:
                ans = (ans * (negpower % UGLYMOD)) % UGLYMOD
                positionOfNeg += 2
            k -= 2
        if k == 1:
            ans = (ans * pos[positionOfPos]) % UGLYMOD
        print(ans)
else:
    pos.sort(reverse = True); positionOfPos = 0
    neg.sort(); positionOfNeg = 0
    ans = 1
    while k > 1:
        try: negpower = neg[positionOfNeg] * neg[positionOfNeg+1]
        except: negpower = -float('inf')
        try: pospower = pos[positionOfPos] * pos[positionOfPos+1]
        except: pospower = -float('inf')
        if pospower >= negpower:
            positionOfPos += 2
            ans = (ans * (pospower % UGLYMOD)) % UGLYMOD
        else:
            ans = (ans * (negpower % UGLYMOD)) % UGLYMOD
            positionOfNeg += 2
        k -= 2
    if k == 1:
        ans = (ans * pos[positionOfPos]) % UGLYMOD
    print(ans)







'''
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
THE LOGIC AND APPROACH IS MINE @luctivud ( UDIT GUPTA )
Link may be copy-pasted here if it's taken from other source.
DO NOT PLAGIARISE.
>>> COMMENT THE STDIN!! CHANGE ONLINE JUDGE !!
'''

Submission status: Wrong Answer

Solution code:
from math import ceil,floor,comb,factorial,gcd,pow,sqrt,log2,cos,sin,tan,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heappop,heappush
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n, k = MAP()
a = sorted(LIST())

if k == 1:
    ans = a[n-1]
elif k % 2 == 0:
    b = sorted([abs(a[i]) for i in range(n)], reverse=True)
    ans = 1
    for i in range(k):
        ans = ( ans * b[i] ) % (10**9+7)
else:
    if a[n-1] == 0:
        ans = 0
    elif a[n-1] < 0:
        ans = 1
        for i in range(k):
            ans = ( ans * a[n-1-i] ) % (10**9+7)
    else:
        b = sorted([abs(a[i]) for i in range(n)], reverse=True)
        ans = 1
        for i in range(k):
            ans = ( ans * b[i] ) % (10**9+7)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=1):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.node_size=len(ls)+1
                self.edges,_=GI(self.node_size,self.node_size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.node_size=int(input())
        else:
            self.node_size=inp_size
        self.edges,_=GI(self.node_size,self.node_size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.node_size=len(ls)+1
        self.edges,_=GI(self.node_size,self.node_size-1,ls,index=index)
        return
 
    def dfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def bfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        while q:
            c=q.popleft()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def parent(self,x):
        return self.dfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)
 
    def topological_sort(self,x):  # return topological sort of the tree
        tps=[]
        q=deque([x])
        v=[None]*self.node_size
        v[x]=0
        while q:
            c=q.popleft()
            tps.append(c)
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=0
        return tps
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.node_size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.node_size
        self.ETout=[-1]*self.node_size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def doubling_LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.depth=[None]*self.node_size
            self.depth=self.bfs(0,func=lambda pr,prv,nxt,dist:prv+1)
            self.par=self.bfs(0,func=lambda pr,prv,nxt,dist:pr)
            self.db=[self.par]
            for i in range(self.node_size.bit_length()):
                #show(self.db)
                self.db+=[[self.db[-1][self.db[-1][i]] for i in range(self.node_size)]]
            self.LCA_init_stat=True
        dx=self.depth[x]
        dy=self.depth[y]
        if dx>dy:
            dx,dy=dy,dx
        c=self.node_size.bit_length()
        while c>0:
            if dx+c<=dy:
                x=self.db[c][x]
                dx+=1<<c
            c>>=1
        
        if x==y:
            return x
        
        c=self.node_size.bit_length()
        while c>0:
            if self.db[c][x]!=self.db[c][y]:
                x=self.db[c][x]
                y=self.db[c][y]
            c>>=1
        
        return self.par[x]
        
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        #self.st=SegTree(self.node_size*2-1,self.ETdepth,function=min,ide=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
    def __str__(self):
        return  str(self.edges)
 
    def show(self):
        if all([all([d==1 for nd,d in e]) for e in self.edges]):
            print( [[nd for nd,d in e] for e in self.edges] )
        else:
            print(self)
 
    def dfs2(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.node_size
        v[x]=root_v
        dfs_tr=[x]
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
                    dfs_tr+=nb,
        return v,dfs_tr

class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    # return boundary index of r such that func({table[i]} =< x , i in [pos,r]
    def right_bound(self,pos,x):
        k=(self.size-pos).bit_length()
        for j in range(k)[::-1]:
            nx=pos+(1<<j)
            if nx<n and self.query(pos,nx+1)<=x:
                pos+=(1<<j)
        return pos
    
    # return boundary index of l such that func({table[i]} =< x , i in [l,pos]
    def left_bound(self,pos,x):
        k=pos.bit_length()
        for j in range(k)[::-1]:
            nx=pos-(1<<j)
            if 0<=nx and self.query(nx,pos+1)<=x:
                pos-=(1<<j)
        return pos

    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)

show_flg=False
show_flg=True

ans=0

#h,w,K=LI()
n,k=LI()
b=LI()
a=sorted(b)
b.sort(key=lambda x:abs(x))

def naive(a,b,n,k):
    ans=-inf
    for p in permutations(range(n)):
        tmp=1
        for i in range(k):
            tmp*=a[p[i]]
        ans=max(tmp,ans)
    return ans

def solve(a,b,n,k):
    pl,mn,zr=[],[],[]
    for i in a:
        if i>0:
            pl+=i,
        elif i<0:
            mn+=i,
        else:
            zr+=i,
        
    def maximize(b,k):
        p,m=0,0
        mn_p,mn_m=inf,inf
        rt=1
        for i in range(k):
            x=b.pop()
            if x>0:
                p+=1
                if mn_p>x:
                    mn_p=x
                    #show('mn_p',mn_p,x)
            elif x<0:
                m+=1
                if mn_m>x:
                    mn_m=-x
                    #show('mn_n',mn_m,x)
            rt*=x
            rt%=mo
        #show(rt)
        st=30
        if m%2==1:
            zp=sorted(b,key=lambda x:abs(x)*(x>0))
            zm=sorted(b,key=lambda x:abs(x)*(x<0))
            
            p_can=zp[-1] if zp and zp[-1]>0 else None
            m_can=zm[-1] if zm else None
            
            if p_can!=None and m_can!=None:
                if p_can/abs(mn_m) > m_can/abs(mn_p):
                    rt*=pow(mn_m,mo-2,mo)
                    rt*=p_can
                    rt%=mo
                    st=31
                    return rt,(st,(p_can,m_can))
                else:# p_can/abs(mn_m) < m_can/abs(mn_p):
                    rt*=pow(mn_p,mo-2,mo)
                    rt*=m_can
                    rt%=mo
                    st=32
                    return rt,st
            elif p_can!=None and m_can==None:
                rt*=pow(mn_m,mo-2,mo)
                rt*=p_can
                rt%=mo
                st=33
                return rt,st
            elif p_can==None and m_can!=None:
                rt*=pow(mn_p,mo-2,mo)
                rt*=m_can
                rt%=mo
                st=34
                return rt,st
    
            while b:
                x=b.pop()
                if x>0:
                    #show('?',rt,rt//mn_m,mn_m,x)
                    rt*=pow(-mn_m,mo-2,mo)
                    #rt//=mn_m
                    rt*=x
                    rt%=mo
                    return rt
                elif x<0 and p>0:
                    rt*=pow(mn_p,mo-2,mo)
                    #rt//=mn_p
                    rt*=x
                    rt%=mo
                    return rt,st
        return rt,st
    
    #M=maximize(b,k)
    #show(M,(M-mo))
    '''
    0 1000000005 -2 ([-1, 1, 1, 1, 2], [-1, 1, 1, 1, 2], 5, 5)
    3 1 2 ([-2, -1, 0, 1, 1], [0, -1], 5, 2)
    '''
    if k+len(zr)==n:
        al=1
        for i in pl:
            al*=i
            al%=mo
        for i in mn:
            al*=i
            al%=mo
        ans=al
        if len(mn)%2==1 and len(zr)>0:
            ans=0
        st=0
    elif k+len(zr)>n:
        ans=0
        st=1
    elif k%2==1 and len(pl)==0: # minus case
        ans=1
        for i in range(k):
            x=b[i]
            ans*=x
            ans%=mo
        if len(zr)>0:
            ans=0
        st=2
    else:
        ans,st=maximize(b,k)
        #st=3

    return ans,st
ans,st=solve(a,b,n,k)
print(ans)

Submission status: Wrong Answer

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

A.sort(reverse=True)

mod=(10**9+7)
p=1
t=0
if k<n:
    for i in range(1,k//2+1):
        if A[k-2*i]*A[k-2*i-1]<A[-2*i]*A[-2*i-1]:
            t+=1


for i in range(k-2*t):
    p=p*A[i]%mod
for i in range(2*t):
    p=p*A[-i-1]%mod


print(p)

Submission status: Wrong Answer

Solution code:
MOD=10**9+7
N,K=map(int,input().split())
import heapq
import numpy as np
A=np.array(sorted(list(map(int,input().split()))))
Am=A[A<0]
Am=np.array([Am[2*i]*Am[2*i+1] for i in range(len(Am)//2)])
A=-A
A=np.vstack([[A],[[1]*len(A)]]).T
Am=-Am
Am=np.vstack([[Am],[[2]*len(Am)]]).T
X=np.vstack([Am,A])
X=X.tolist()
heapq.heapify(X)
ans=1
while K>0:
  x=heapq.heappop(X)
  if x[1]<=K:
    ans*=(-1*x[0])
    K-=x[1]
    
print(ans%MOD)

Submission status: Wrong Answer

Solution code:
N,K = list(map(int,input().split()))
a = list(map(int,input().split()))
a.sort()
large = 10**9 + 7
num_minus = 0
for k in range(N):
    if a[k] < 0:
        num_minus += 1

if num_minus == N and K%2 == 1:
    ans = 1
    for i in range(K):
        #print(a[K-1-i],K-1-i)
        ans *= a[N-1-i]
        ans = ans % large
    print(ans)
    exit()

large = 10**9 + 7

i_left = 0
i_right = N-1

if K == 1:
    print(a[i_right])
    exit()
ans = 1


if N - num_minus < K and K%2 == 1:
    ans = 1
    for i in range(K):
        #print(a[K-1-i],K-1-i)
        ans *= a[N-1-i]
        ans = ans % large
    print(ans)
    exit()


while K > 1:
    #print(i_right,i_left)
    if a[i_right]*a[i_right-1] >= a[i_left]*a[i_left+1]:
        ans = ans * a[i_right]
        ans = ans % large
        ans = ans * a[i_right-1]
        ans = ans % large
        i_right -= 2
    else:
        ans = ans * a[i_left]
        ans = ans % large
        ans = ans * a[i_left+1]
        ans = ans % large
        i_left += 2

    K -= 2

if K == 0:
    print(ans)
else:
    ans = ans * a[i_right]
    ans = ans % large
    print(ans)