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:
def main():
    n,k = map(int,input().split())
    A = list(map(int,input().split()))

    MOD = 10**9 + 7

    absA = [abs(a) for a in A]
    flg = 0
    m = []
    p = []
    dict = []
    T = []
    for i in A:
        if i < 0:
            m.append(i)
            T.append(tuple([abs(i),-1]))
        elif i > 0:
            p.append(i)
            T.append(tuple([abs(i),1]))
        else:
            flg = 1

    T.sort(reverse=True)


    ans = T[:k]
    c = 0
    for i in ans:
        if i[1] == -1:
            c += 1

    if c % 2 == 0:
        l = 1
        for i in ans:
            l *= i[0]
            l %= MOD
        print(l)

    else:
        flg_1,flg_2 = 0,0
        for j in range(k-1,-1,-1):
            if T[j][1] == -1:
                flg_1 = 1
                min_m = T[j][0]
                break

        for j in range(k,len(T)):
            if T[j][1] == 1:
                flg_2 ^= 1
                # print('AaA')
                max_p = T[j][0]
                break

        # print(min_m,max_p)

        if flg_1 and flg_2:
            flg = 1
        else:
            flg = 0

        flg_1,flg_2 = 0,0

        for j in range(k-1,-1,-1):
            if T[j][1] == 1:
                flg_1 = 1
                min_p = T[j][0]
                break
        
        for j in range(k,len(T)):
            if T[j][1] == -1:
                flg_2 = 1
                max_m = T[j][0]
                break

        if flg_1 and flg_2:
            flg2 = 1
        else:
            flg2 = 0


        l = 1
        for i in ans:
            l *= abs(i[0])
            l %= MOD 

        # print(l)

        if flg == 1 and flg2 == 1:
            if min_p * max_p >= min_m * max_m:
                l *= max_p
                l *= pow(min_m,MOD-2,MOD)
            else:
                l *= max_m
                l *= pow(min_p,MOD-2,MOD)
        elif flg == 1:
                l *= max_p
                l *= pow(min_m,MOD-2,MOD)
        elif flg2 == 1:
                l *= max_m
                l *= pow(min_p,MOD-2,MOD)
        else:
            if 0 in A:
                l = 0
            else:
                A.sort(reverse=True)
                l = 1
                for i in range(k):
                    l *= A[i]
                    l %= MOD
                print(l)
                exit()

            
        print(l%MOD)

Submission status: Wrong Answer

Solution code:
N,K=list(map(int,input().split()))
a=list(map(int,input().split()))
a.sort(key=lambda x:abs(x),reverse=True)

mod=10**9+7

p=[]
m=[]
zero=False
cntm=0
cntp=0

for aa in a:
    if aa>=0:
        p.append(aa)
        if cntp+cntm<K:
            cntp+=1
    else:
        m.append(-aa)
        if cntp+cntm<K:
            cntm+=1
    
    if aa==0:
        zero=True

ans=1

if cntm%2==1:
    cntm-=1
    cntp+=1

    if cntp>len(p):
        for i in range(K):
            ans*=a[N-i-1]
            ans=(ans+mod*mod)%mod
        
        if zero:
            print(0)
        else:
            print(ans)
        exit(0)

for i in range(cntm):
    ans*=m[i]
    ans%=mod
for i in range(cntp):
    ans*=p[i]
    ans%=mod

print(ans)

Submission status: Wrong Answer

Solution code:
# import time
# t1=time.time()
def LI():return list(map(int,input().split()))
def I(): return int(input())
from collections import deque, Counter, defaultdict
# from heapq import heappop, heappush
# from pprint import pprint
# import numpy as np
# import itertools

MOD=10**9+7

n,k=LI()
a=LI()
if k==1:
    a.sort()
    print(a[-1]%MOD)
    exit()
if n==k:
    ans=1
    for i in range(k):
        ans=ans*a[i]%MOD
    print(ans)
    exit()
    
minus=[]
plus=[]
for q in a:
    if q>=0:
        plus.append(q)
    else:
        minus.append(q)
if len(plus)==n:
    plus.sort(reverse=True)
    ans=1
    for i in range(k):
        ans=ans*plus[i]%MOD
    print(ans)
    exit()
    
if len(minus)==n:
    if k%2==0:
        minus.sort()
        ans=1
        for i in range(k):
            ans=ans*minus[i]%MOD
        print(ans)
        exit()
    else:
        minus.sort(reverse=True)
        ans=1
        for i in range(k):
            ans=ans*minus[i]%MOD
        print(ans)
        exit()
      
if k%2==0 or k%2==1:
    if len(minus)==1:
        plus.sort(reverse=True)
        ans=1
        for i in range(k):
            ans=ans*plus[i]%MOD
        print(ans)
        exit()
    if len(minus)>=2:
        minus.sort()
        minus=deque(minus)
        while True:
            if len(minus)<=1:
                break
            a=minus.popleft()
            b=minus.popleft()
            plus.append(a*b)
            k-=1
            if k==1:
                break
    plus.sort(reverse=True)
    ans=1
    for i in range(k):
        ans=ans*plus[i]%MOD
    print(ans)
    exit()

    
    

#     b.append(q%MOD)
# b.sort(reverse=True)
# print(b)
# ans=1
# for i in range(k):
#     ans=ans*b[i]%MOD
# print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
sorted(a, key=lambda x: abs(x))
mod = 10**9 + 7
a.reverse()
ans = 1
kk = 0
for i in range(k):
    if a[i] < 0:
        kk += 1
if kk %2 == 0:
    for i in range(k):
        ans = ans*abs(a[i])%mod
    print(ans)
else:
    ans = 1
    plus = -1
    for i in range(n):
        if a[i] > 0:
            plus = 1
            break
    if plus == 1:
        for i in range(k-1):
            ans = ans*abs(a[i])%mod
        for j in range(i,n):
            if a[j] > 0:
                print(ans*a[j]%mod)
    else:
        ans = 1
        for i in range(n):
            if a[i] == 0:
                plus = 0
                break
        if plus == 0:
            print(0)
        else:
            a.reverse()
            for i in range(k):
                ans = ans*a[i]%mod
            print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
p=[]
m=[]
z=0
a.sort(reverse=True)
for i in range(n):
    if a[i]>0:
        p.append(a[i])
    elif a[i]==0:
        z+=1
    else:
        m.append(a[i])
nump=len(p)
numm=len(m)
ans=1
if nump+numm<k:
    print(0)
elif numm<2 and nump>=k:
    for i in range(k):
        ans*=p[i]
        ans%=10**9+7
    print(ans)
elif 2*(numm//2)+nump<k: #2
    if z!=0:
        print(0)
    else:
        for i in range(k):
            ans*=a[i]
            ans%=10**9+7
        print(ans)
elif  nump==0: #8?
    if z!=0 and k%2==1:
        print(0)
    elif z!=0 and numm<k:
        print(0)
    else:
        if k%2==0:
            m.sort()
            for i in range(k):
                ans*=m[i]
                ans%=10**9+7
        else:
            m.sort(reverse=True)
            for i in range(k):
                ans*=m[i]
                ans%=10**9+7
        print(ans)
else:
    if k%2==1:
        ans*=p[0]
    m.sort()
    nump=(nump-1)//2
    numm=numm//2
    nump1=0
    nump2=0
    numm1=0
    numm2=0
    for i in range(k//2):
        if nump2==nump:
            nump1=-1
        else:
            nump1=p[nump2*2]*p[nump2*2+1]
        if numm2==numm:
            numm1=-1
        else:
            numm1=m[numm2*2]*m[numm2*2+1]
        if numm1>=nump1:
            num=numm1
            numm2+=1
        else:
            num=nump1
            nump2+=1
        ans*=num
        ans%=10**9+7
    print(ans)

Submission status: Wrong Answer

Solution code:
def resolve():
    N,K = map(int,input().split())
    A = list(map(int,input().split()))
    pls = [i for i in A if i > 0]
    ms = [i for i in A if i <0]
    pls.sort(reverse=True)
    ms.sort(reverse=False)
    A.sort(key = lambda x : abs(x),reverse=True)
    if len(pls)+len(ms) < K:
        print(0)
        return
    if len(pls) == 0 and K %2 == 1:
        if len(ms) != N:
            print(0)
            return
        x=1
        for i in list(reversed(ms))[:K]:
            x*= abs(i)
            x%= 10**9+7

        print((-x)%10**9+7)
        return
    if len(pls)+len(ms) == K and K %2==1:
        print(0)
        return

    pc = 0
    mc = 0
    for i in range(K):
        if pc >= len(pls):
            mc+=1
        elif mc >= len(ms):
            pc+=1
        elif pls[pc] > abs(ms[mc]):
            pc +=1
        else:
            mc +=1

    if mc%2  !=0:
        aplan=0
        bplan=0
        if mc < len(ms)-1:
            aplan = abs(ms[mc] *ms[mc-1])
        if pc < len(pls)-1:
            bplan = abs(pls[pc]*pls[pc-1])
        
        if aplan>bplan:
            pc -=1
            mc +=1
        else:
            pc +=1
            mc -=1
    result=1
    for i in pls[:pc]:
        result*=i
        result%=10**9+7
    for i in ms[:mc]:
        result*=abs(i)
        result%=10**9+7
    print(result)


resolve()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from collections import deque
MOD = 1000000007  # type: int


def solve(N: int, K: int, A: "List[int]"):
    mp = sum([int(a<=0) for a in A])
    pl = True
    if (N == K):
        if mp%2 == 0:     pl = True
        else:     pl = False
    if (mp == N):
        if K%2 == 0: pl = True
        else: pl = False

    absA = sorted(A, key=abs)
    sA = deque(absA)
    ans = 1
    if pl:
        for i in range(K):
            ans*= sA.pop()
            ans%= MOD

        if ans<0:
            pre=absA[i]
            prei = i
            while((i!=N) or (absA[i] * pre)>0 ): i+=1
            if i==N:
                pre = avsA[prei+1]
                i = prei
                while((absA[i]*pre)>0 ): i-=1
            
            ans//= absA[i]
            ans*= pre

        print(ans%MOD)

    else:
        for i in range(K):
            ans*= sA.popleft()
            ans%= MOD
        print(ans%MOD)


    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, K, A)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
N,K=map(int, sys.stdin.readline().split())
A=map(int, sys.stdin.readline().split())
AA=[]
for a in A:
    if a<0:
        a*=-1
    AA.append(a)
AA.sort(reverse=True)

mod=10**9+7
ans=1
for i,a in enumerate(AA):
    ans*=a
    ans%=mod
    if i==K-1:
        print ans
        quit()

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
mod=10**9+7
P=[]
Z=[]
N=[]
for i in range(n):
  if a[i]>0:
    P.append(a[i])
  elif a[i]==0:
    Z.append(a[i])
  else:
    N.append(-a[i])
P.sort()
P3=[1]
for i in range(len(P)):
  P3.append(P3[-1]*P[i]%mod)
P.reverse()
P2=[1]
for i in range(len(P)):
  P2.append(P2[-1]*P[i]%mod)
N.sort()
N3=[1]
for i in range(len(N)):
  N3.append(N3[-1]*N[i]%mod)
N.reverse()
N2=[1]
for i in range(len(N)):
  N2.append(N2[-1]*N[i]%mod)

if n==k:
  ans=1
  for i in range(n):
    ans*=a[i]
    ans%=mod
  print(ans%mod)
  exit()

if k==1:
  print(max(a)%mod)
  exit()

if len(P)+len(N)<k:
  print(0)
  exit()

if len(N)==0:
  print(P2[k]%mod)
  exit()

if len(P)+len(N)==k:
  if len(N)%2==0:
    print(P2[-1]*N2[-1]%mod)
    exit()
  else:
    if len(Z)!=0:
      print(0)
    else:
      print(-P2[-1]*N2[-1]%mod)
    exit()

if k%2==0:
  ans=1
  xp=0
  xn=0
  for i in range(k//2):
    if xp+1<len(P):
      xa=P[xp]*P[xp+1]
    else:
      xa=1
    if xn+1<len(N):
      xb=N[xn]*N[xn+1]
    else:
      xb=1
    if xa<xb:
      xn+=2
      ans*=xb
      ans%=mod
    else:
      xp+=2
      ans*=xa
      ans%=mod
  print(ans%mod)

else:
  ans=1
  xp=0
  xn=0
  ctP=0
  ctN=0
  for i in range(k//2):
    if xp+1<len(P):
      xa=P[xp]*P[xp+1]
    else:
      xa=0
    if xn+1<len(N):
      xb=N[xn]*N[xn+1]
    else:
      xb=0
    if xa<xb:
      xn+=2
      ans*=xb
      ans%=mod
      ctN+=1
    else:
      xp+=2
      ans*=xa
      ans%=mod
      ctP+=1
  if ctP*2+1<=len(P):
    ans*=P[ctP*2]
    ans%=mod
    print(ans%mod)
  else:
    N.reverse()
    P.reverse()
    ans=1
    xp=0
    xn=0
    ctP=0
    ctN=0
    for i in range(k//2):
      if xp+1<len(P):
        xa=P[xp]*P[xp+1]
      else:
        xa=0
      if xn+1<len(N):
        xb=N[xn]*N[xn+1]
      else:
        xb=0
      if xa<xb:
        xn+=2
        ans*=xb
        ans%=mod
        ctN+=1
      else:
        xp+=2
        ans*=xa
        ans%=mod
        ctP+=1
    ans*=N[ctN*2]
    ans%=mod
    if len(Z)!=0:
      print(0)
    else:
      print(-ans%mod)

Submission status: Wrong Answer

Solution code:
import sys
N, K = map(int, input().split())
A = list(map(int, input().split()))
A.sort(reverse=True)
mod = 10**9+7
T = {"mi":0, "pu":0, "zero":0}
M = []
P = []
for i in range(N):
    if A[i] < 0:
        T["mi"] += 1
        M.append(A[i])
    elif A[i] == 0:
        T["zero"] += 1
    else:
        T["pu"] += 1
        P.append(A[i])

M.sort(reverse=True)
ans = 1
if K > T["pu"]+T["mi"]:
    print(0)
    sys.exit()
if T["mi"] == 1 and K > T["pu"]:
    for i in range(N):
        ans *= A[i]
        ans %= mod
    if T["zero"] != 0:
        ans = 0
    print(ans)
    sys.exit()
if T["pu"] == 0:
    if K % 2 == 1:
        for i in range(K):
            ans *= A[i]
            ans %= mod
        if T["zero"] != 0:
            ans = 0
    else:
        for i in range(K):
            A.sort()
            ans *= A[i]
            ans %= mod
    print(ans)
    sys.exit()

i = 0
j = 0
while(True):
    if K == 0:
        break
    if K == 1:
        if i < len(P):
            ans *= P[i]
        else:
            ans *= M[j]
        ans %= mod
        break
    if i + 1 >= len(P) and j + 1 >= len(M):
        ans *= P[i]*M[j]
        ans %= mod
        break
    elif i + 1 >= len(P):
        ans *= M[j]*M[j+1]
        ans %= mod
        j += 2
        K -= 2
    elif j + 1 >= len(M):
        ans *= P[i]*P[i+1]
        ans %= mod
        i += 2
        K -= 2
    elif P[i]*P[i+1] >= M[j]*M[j+1]:
        ans *= P[i]*P[i+1]
        ans %= mod
        i += 2
        K -= 2
    else:
        ans *= M[j]*M[j+1]
        ans %= mod
        j += 2
        K -= 2
if ans < 0 and T["zero"] != 0:
    ans = 0
print(ans)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
A.sort()
A.reverse()
ans=1
inf=10**9+7
pos=sum(1 for x in A if x>=0)

if K%2==0:
    temp=list(abs(ai) for ai in A)
    temp.sort()
    temp.reverse()
    for i in range(K):
        ans*=temp[i]
        if i%2==1:
            ans=ans%inf
elif K<=pos:
    for i in range(int((K-1)/2)):
        small=A[0]*A[1]
        big=A[len(A)-2]*A[len(A)-1]
        if small<=big:
            ans*=big
            del A[len(A)-2:len(A)]
        else:
            ans*=small
            del A[0:2]
        if i%2==1:
            ans=ans%inf   
    ans*=max(A[0],A[len(A)-1])
    ans=ans%inf
else:
    temp=list(abs(ai) for ai in A)
    temp.sort()
    for i in range(K):
        ans*=temp[i]
        if i%2==1:
            ans=ans%inf
    ans*=-1
    ans=ans%inf


print(ans)

Submission status: Wrong Answer

Solution code:
# Required function 
n, k = map(int, input().split())
A = list(map(int, input().split()))
# print(len(A))
A.sort() 
ans = 1
mod = 1000000007
if (A[n - 1] == 0 and (k & 1)): 
    print(0)
elif (A[n - 1] <= 0 and (k & 1)) : 
    for i in range(n - 1, n - k + 1, -1): 
        ans = ans * A[i] % mod 
    ans = (ans + mod) % mod
    print(ans % mod)
else:
    i = 0
    j = n - 1
    if (k & 1): 
        ans *= A[j] 
        j-= 1
        k-=1
    k >>= 1
    for itr in range( k) : 
        left_ans = A[i] * A[i + 1] % mod
        right_ans = A[j] * A[j - 1] % mod
        if (left_ans > right_ans) : 
            ans = ans * left_ans % mod
            i += 2
            
        else : 
            ans = ans * right_ans % mod
            j -= 2
    # print(ans)
    ans = (ans + mod) % mod
    print(ans % mod)

Submission status: Wrong Answer

Solution code:
MOD = 10**9 + 7

N, K = list(map(int, input().split()))
As = list(map(int, input().split()))

A_pos = [a for a in As if a >= 0]
A_pos.sort()
A_pos.reverse()

A_neg = [a for a in As if a < 0]
A_neg.sort()

ans = 1

pos_used = 0
neg_used = 0

pos_total = len(A_pos)
neg_total = len(A_neg)

# 答えが負になるかチェック
if pos_total < K and (K-pos_total)%2 == 1:
    # 小さい方から取る
    A_pos.reverse()
    A_neg.reverse()


k = K
# 二つずつペアで見てゆく
while (pos_used+neg_used) < K:
    # Kが1
    if K == 1:
        if N == 1:
            if pos_total == 1:
                ans = (ans * A_pos[0]) % MOD
            else:
                ans = (ans * A_neg[0]) % MOD
        else:
            if pos_total > 0:
                ans = (ans * A_pos[0]) % MOD
            else:
                ans = (ans * A_neg[0]) % MOD
        break

    # のこり2以上のとき
    if K-(pos_used+neg_used) >= 2:
        # 正の数，負の数とも二つ以上残っているとき
        if (pos_total-pos_used)>=2 and (neg_total-neg_used)>=2:
            if A_neg[neg_used]*A_neg[neg_used+1] >= A_pos[pos_used]*A_pos[pos_used+1]:
                ans = (ans * A_neg[neg_used] * A_neg[neg_used+1]) % MOD
                neg_used += 2
            else:
                ans = (ans * A_pos[pos_used] * A_pos[pos_used+1]) % MOD
                pos_used += 2

        # もう正の数しか残っていない時
        elif neg_total == neg_used:
            ans = (ans * A_pos[pos_used] * A_pos[pos_used+1]) % MOD
            pos_used += 2

        # もう負の数しか残っていない時
        elif pos_total == pos_used:
            ans = (ans * A_neg[neg_used] * A_neg[neg_used+1]) % MOD
            neg_used += 2

    # のこり一つのとき
    else:
        # もう正の数しか残っていない時
        if neg_total == neg_used:
            ans = (ans * A_pos[pos_used]) % MOD
            pos_used += 1

        # もう負の数しか残っていない時
        elif pos_total == pos_used:
            ans = (ans * A_neg[neg_used]) % MOD
            neg_used += 1

print(ans)

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_m = min(ans_m, 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:
N,K = map(int,input().split())
def checkio(numbers_array):
    return sorted(numbers_array, key=lambda x: abs(x))
A = list(map(int,input().split()))
B = checkio(A)
ans = 1
mins = 0
minh = 0
aans = 1
for i in range(K):
    aans *= B[i]
for i in range(K):
    now = B.pop()
    ans *= now
    if now > 0:
        mins = now
    else:
        minh = now

ms = 0
mh = 0
aa = 0
aa2 = 0
if ans > 0:
    print(ans%(10**9+7))
else:
    for i in range(N-K):
        n = B.pop()
        if n > 0:
            ms = n
        else:
            mh = n
        if ms != 0 and mh != 0:
            break
    if ms != 0 and minh != 0:
        aa = ans//minh*ms
    if mh != 0 and mins != 0:
        aa2 = ans//mins*mh
    ans = max(aa, aa2)
    if ans == 0:
        ans = aans
    print(ans%(10**9+7))

Submission status: Wrong Answer

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(ans)

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

Submission status: Wrong Answer

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

P = []
N = []
z = 0
for i in A:
  if i > 0:
    P.append(i)
  elif i < 0:
    N.append(i)
  else:
    z += 1
P.sort(reverse = True)
N.sort()

ans = 1
sig = 1
if len(P) + (len(N)// 2) * 2 < K and z > 0:# Conner_1
  ans = 0
elif len(P) == 0 and K % 2 == 1:# Conner_2
  for i in range(K):
    ans *= N[-i-1]
    ans %= base
else:#Not use zeros and (P exists or even K)
  x = 0
  y = 0
  for i in range(K):
    if x == len(P):
      ans *= N[y]
      y += 1
      sig = sig * (-1)
      continue
    if y == len(N):
      ans *= P[x]
      x += 1
      ans %= base
      continue
    if y == len(N) - 1 and sig > 0:# ans must be positive
      ans *= P[x]
      x += 1
      ans %= base
      continue
    if x == len(P) - 1:
      if sig > 0 and (K - i) % 2 == 1 or sig < 0 and (K - i) % 2 == 0:
        ans *= P[x]
        x += 1
      else:
        ans *= N[y]
        y += 1
        sig = sig * (-1)
      ans %= base
      continue
    if P[x] > abs(N[y]):
      ans *= P[x]
      x += 1
    else:
      ans *= N[y]
      y += 1
      sig = sig * (-1)
    ans %= base
print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
mod = 10**9 + 7
b_p = []
b_n = []
ab = []
for i in range(n):
    ab.append([abs(a[i]), a[i]])
    if a[i] >= 0:
        b_p.append(a[i])
    else:
        b_n.append(a[i])
b_p = sorted(b_p,reverse=True)
b_n = sorted(b_n)
ab.sort(key= lambda val : val[0])
ans = 1
i = 0
x = 0
y = 0
if k%2 == 1:
    if len(b_p) >= 1:
        ans *= b_p[0]
        x += 1
        i += 1
while i < k-1:
    i += 2
    if x < len(b_p)-1 and y < len(b_n)-1:
        if b_p[x]*b_p[x+1] > b_n[y]*b_n[y+1]:
            ans *= b_p[x]*b_p[x+1]
            ans %= mod
            x += 2
        else:
            ans *= b_n[y]*b_n[y+1]
            ans %= mod
            y += 2
    
    elif x < len(b_p)-1:
        ans *= b_p[x]*b_p[x+1]
        ans %= mod
        x += 2
    elif y < len(b_n)-1:
        ans *= b_n[y]*b_n[y+1]
        ans %= mod
        y += 2
    
if i != k:
    if 0 in b_p:
        ans = 0
    else:
        ans = 1
        for i in range(k):
            ans *= ab[i][1]
            ans %= mod
        
print(ans%mod)

Submission status: Wrong Answer

Solution code:
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
import numpy as np

n,k=nii()
a=lnii()
a_abs=[abs(i) for i in a]

sort_inx=list(np.argsort(a_abs))
sort_inx=sort_inx[::-1]

seihu=[]
for i in sort_inx:
  if a[i]>0:
    seihu.append(1)
  elif a[i]<0:
    seihu.append(-1)
  else:
    seihu.append(0)

a_abs.sort(reverse=True)
mod=10**9+7

if k==1:
  print(a_abs[0])
  exit()

l=a_abs[:k]
if 0 in l:
  print(0)
  exit()

def calc(l):
  ans=1
  for i in l:
    ans*=i
    ans%=mod
  return ans%mod

if seihu[:k].count(-1)%2==0:
  ans=calc(l)
  print(ans)
  exit()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N,K = IL()
temp = IL()
IS_Z = None
A = []
for a in temp:
  if a!=0:
    A.append(a)
  if a==0:
    IS_Z = True
A = sorted(A,key= lambda x:(-abs(x),x))
S = [a//abs(a) if abs(a)!=0 else 0 for a in A]

NA = len(A)
if NA<K:
  print(0)
  exit()
  
count_M = 0
last_M = None
last_P = None
for i in range(K):
  if S[i] == -1:
    last_M = i
    count_M += 1
  if S[i] == 1:
    last_P = i


if count_M%2 == 0:
  ans = 1
  for i in range(K):
    ans *= A[i]
    ans %= MOD
  print(ans)
  exit()

else:
  ANS1 = -INF
  ANS2 = -INF
  if last_M!=None:
    for i in range(K,NA):
      if S[i] == 1:
        ans = 1
        for ii in range(K):
          if ii != last_M:
            ans *= A[ii]
            ans %= MOD
        ans *= A[i]
        ans %= MOD
        ANS1 = ans
        break
  if last_P!=None:
    for i in range(K,NA):
      if S[i] == -1:
        ans = 1
        for ii in range(K):
          if ii != last_P:
            ans *= A[ii]
            ans %= MOD
        ans *= A[i]
        ans %= MOD
        ANS2 = ans
        break
  print(ANS1,ANS2)
  if max(ANS1,ANS2)!=-INF:
    print(max(ANS1,ANS2))
    exit()
  if IS_Z:
    print(0)
    exit()
  else:
    ans = 1
    for i in range(K):
      ans *= A[NA-1-i]
      ans %= MOD
    print(ans)

Submission status: Wrong Answer

Solution code:
import itertools, collections

n, k = map(int,input().split())

a = list(map(int,input().split()))

mod_num = 10 ** 9 + 7

a.sort(reverse=True)

left = 0
right = -1

ans = 1

while k >= 2:
    if a[left] * a[left + 1] < a[right] * a[right - 1]:
        ans *= a[right] * a[right - 1] % mod_num
        right -= 2
    else:
        ans *= a[left] * a[left + 1] % mod_num
        left += 2
    k -= 2

if k == 1:
    print(ans * a[left] % mod_num)
else:
    print(ans)