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 numpy as np
import collections
N,K=map(int, input().split())
A =list(map(int,input().split()))
MOD = 10 ** 9 + 7

if N==K:
  ans0 = 1
  for a in A[0:N]:
    ans0 *= a
    ans0 %= MOD
  print(ans0)
  exit()
A=sorted(A)  
if (K%2==1 and A[-1]<0):
  ans1 = 1
  for a in A[N-K:N]:
    ans1 *= a
    ans1 %= MOD
  print(ans1)
  exit()

A=sorted(A, key=lambda x:abs(x), reverse=True)
AA=[np.sign(i) for i in A]

ansA = 1
for a in A[0:K]:
  ansA *= a
  ansA %= MOD
ansAA = AA[0:K].count(-1)%2

if ansAA=0:
  print(ansA)
  exit()

B=sorted(A[K-1:N])

if AA[K-1]>0:
  ansB=ansAA//A[K-1]*B[0]
else:ansB=ansAA//A[K-1]*B[-1]

print(ansB)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
from functools import reduce
from operator import add, mul
 
N,K=map(int, input().split())
A =list(map(int,input().split()))
MOD = 10 ** 9 + 7

A=sorted(A)
#print(A)
ansA = 1
for a in A[0:K]:
  ansA *= a
  if ansA>0:ansA %= MOD
A=sorted(A, reverse=True)
ansB = 1
for a in A[0:K]:
  ansB *= a
  if ansB>0:ansB %= MOD

A=sorted(A, key=lambda x:abs(x), reverse=True)
ansC = 1
for a in A[0:K]:
  ansC *= a
  if ansC>0:ansC %= MOD

#print(ansA, ansB, ansC)
print(max(ansA, ansB, ansC)%MOD)
exit()
#print(factorial(0,30))
      
#A=sorted(A)
 
#Amin=factorial(0,K)
#if Amin<0 and 0 in A[K:N]:Amin=0

A=sorted(A, reverse=True)
 
Amax=factorial(0,K)
 
#A=sorted(A, key=lambda x: abs(x), reverse=True)
 
#B=A[0:K-1]
#C=A[K-1:N]
 
#Bmax=factorial(0,K-1)*C[0]
#print(factorial(0,K-1),C[0])
#print(Bmax)
 
#C=sorted(C)
#print(C)
#Bmin=factorial(0,K-1)*C[0]
#print(Bmin)
#print(Amax,Amin,Bmax,Bmin)
#print(max(Amax,Amin,Bmax,Bmin)%(10**9+7))
print(Amax)import numpy as np
import sys
from functools import reduce
from operator import add, mul
 
N,K=map(int, input().split())
A =list(map(int,input().split()))
MOD = 10 ** 9 + 7

A=sorted(A)
#print(A)
ansA = 1
for a in A[0:K]:
  ansA *= a
  if ansA>0:ansA %= MOD
A=sorted(A, reverse=True)
ansB = 1
for a in A[0:K]:
  ansB *= a
  if ansB>0:ansB %= MOD

A=sorted(A, key=lambda x:abs(x), reverse=True)
ansC = 1
for a in A[0:K]:
  ansC *= a
  if ansC>0:ansC %= MOD

#print(ansA, ansB, ansC)
print(max(ansA, ansB, ansC)%MOD)
exit()
#print(factorial(0,30))
      
#A=sorted(A)
 
#Amin=factorial(0,K)
#if Amin<0 and 0 in A[K:N]:Amin=0

A=sorted(A, reverse=True)
 
Amax=factorial(0,K)
 
#A=sorted(A, key=lambda x: abs(x), reverse=True)
 
#B=A[0:K-1]
#C=A[K-1:N]
 
#Bmax=factorial(0,K-1)*C[0]
#print(factorial(0,K-1),C[0])
#print(Bmax)
 
#C=sorted(C)
#print(C)
#Bmin=factorial(0,K-1)*C[0]
#print(Bmin)
#print(Amax,Amin,Bmax,Bmin)
#print(max(Amax,Amin,Bmax,Bmin)%(10**9+7))
print(Amax)

Submission status: Runtime Error

Solution code:
4 2
1 2 -3 -4

Submission status: Runtime Error

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

def how_many_minus(list):
    # リスト中の負の数の個数
    ans = 0
    for i in range(len(list)):
        if list[i] < 0:
            ans += 1
    return ans

if N == K:
    chosen = A
else:
    minus = how_many_minus(A)  # 負の数の個数
    if minus == N and K % 2 == 1:  # 全て負の数でKが奇数
        A.sort(key=lambda x: abs(x))
        chosen = A[:K]  # 答えは負なので絶対値の小さい方からK個選ぶ
    else:
        # 答えは正にできる
        A.sort(key=lambda x: abs(x), reverse=True)
        chosen = A[:K]  # 絶対値が大きい方からK個

        minus_K = how_many_minus(chosen)
        if minus_K % 2 == 1:  # 絶対値が大きい方からK個の積が負
            for i in range(K):
                if chosen[i] < 0:
                    x_m = chosen[i]  # 絶対値最小の負の数
                    x_m_i = i
                if chosen[i] >= 0:
                    x_p = chosen[i]  # 絶対値最小の非負の数
                    x_p_i = i
            for i in range(N - 1, K - 1, -1):
                if A[i] < 0:
                    y_m = A[i]  # 絶対値最大の負の数
                if A[i] >= 0:
                    y_p = A[i]  # 絶対値最大の非負の数
            # P = 選んだK個の積として、|P/x_m * y_p| と |P/x_p * y_m| のどちらが大きいかみる
            # すなわち |x_p * y_p| と |x_m * y_m| の大小
            if abs(x_p * y_p) <= abs(x_m * y_m):
                chosen[x_p_i] = y_m
            else:
                chosen[x_m_i] = y_p

ans = 1
for i in range(K):
    ans *= A[i] % mod
    ans %= mod

print(ans)

Submission status: Runtime Error

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

def how_many_minus(list):
    # リスト中の負の数の個数
    ans = 0
    for i in range(len(list)):
        if list[i] < 0:
            ans += 1
    return ans

if N == K:
    chosen = A
else:
    minus = how_many_minus(A)  # 負の数の個数
    if minus == N and K % 2 == 1:  # 全て負の数でKが奇数
        A.sort(key=lambda x: abs(x))
        chosen = A[:K]  # 答えは負なので絶対値の小さい方からK個選ぶ
    else:
        # 答えは正にできる
        A.sort(key=lambda x: abs(x), reverse=True)
        chosen = A[:K]  # 絶対値が大きい方からK個

        minus_K = how_many_minus(chosen)
        if minus_K % 2 == 1:  # 絶対値が大きい方からK個の積が負
            for i in range(K):
                if chosen[i] < 0:
                    x_m = chosen[i]  # 絶対値最小の負の数
                    x_m_i = i
                if chosen[i] => 0:
                    x_p = chosen[i]  # 絶対値最小の非負の数
                    x_p_i = i
            for i in range(N - 1, K - 1, -1):
                if A[i] < 0:
                    y_m = A[i]  # 絶対値最大の負の数
                if A[i] => 0:
                    y_p = A[i]  # 絶対値最大の非負の数
            # P = 選んだK個の積として、|P/x_m * y_p| と |P/x_p * y_m| のどちらが大きいかみる
            # すなわち |x_p * y_p| と |x_m * y_m| の大小
            if abs(x_p * y_p) <= abs(x_m * y_m):
                chosen[x_p_i] = y_m
            else:
                chosen[x_m_i] = y_p

ans = 1
for i in range(K):
    ans *= A[i] % mod
    ans %= mod

print(ans)

Submission status: Runtime Error

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

def how_many_minus(list):
    # リスト中の負の数の個数
    ans = 0
    for i in range(len(list)):
        if list[i] < 0:
            ans += 1
    return ans

if N == K:
    chosen = A
else:
    minus = how_many_minus(A)  # 負の数の個数
    if minus == N and K % 2 == 1:  # 全て負の数でKが奇数
        A.sort(key=lambda x: abs(x))
        chosen = A[:K]  # 答えは負なので絶対値の小さい方からK個選ぶ
    else:
        # 答えは正にできる
        A.sort(key=lambda x: abs(x), reverse=True)
        chosen = A[:K]  # 絶対値が大きい方からK個

        minus_K = how_many_minus(chosen)
        if minus_K % 2 == 1:  # 絶対値が大きい方からK個の積が負
            for i in range(K):
                if chosen[i] < 0:
                    x_m = chosen[i]  # 絶対値最小の負の数
                    x_m_i = i
                if chosen[i] > 0:
                    x_p = chosen[i]  # 絶対値最小の正の数
                    x_p_i = i
            for i in range(N - 1, K, -1):
                if A[i] < 0:
                    y_m = A[i]  # 絶対値最大の負の数
                if A[i] > 0:
                    y_p = A[i]  # 絶対値最大の正の数
            # P = 選んだK個の積として、|P/x_m * y_p| と |P/x_p * y_m| のどちらが大きいかみる
            # すなわち |x_p * y_p| と |x_m * y_m| の大小
            if abs(x_p * y_p) <= abs(x_m * y_m):
                chosen[x_p_i] = y_m
            else:
                chosen[x_m_i] = y_p

ans = 1
for i in range(K):
    ans *= A[i] % mod
    ans %= mod

print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
A=list(map(int,input().split()))
mod=10**9+7
P=[]
M=[]
for i in range(n):
  if A[i]>=0:
    P.append(A[i])
  else:
    M.append(A[i])

P.sort(reverse=True)
plen=len(P)
M.sort()
mlen=len(M)
if mlen==0:
  ans=1
  for i in range(k):
    ans*=P[i]%mod
  ans%=mod
  print(ans)
elif plen==0:
  ans=1
  if k%2==1:
    for i in range(mlen-1,mlen-k-1,-1):
      ans*=M[i]%mod
    ans%=mod
    print(ans)
  else:
    for i in range(k):
      ans*=M[i]%mod
    ans%=mod
    print(ans)
else:
  AP=[1]*(plen+1)
  AM=[1]*(mlen+1)
  for i in range(1,plen+1):
    AP[i]=AP[i-1]*P[i-1]%mod
  for j in range(1,mlen+1):
    AM[j]=AM[j-1]*abs(M[j-1])%mod
  ans=-float('inf')
  for i in range(0,min((k//2)*2,mlen)+1,2):
    p=1
    p*=AM[i]%mod
    p*=AP[k-i]%mod
    ans=max(ans,p)
  print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
m=[]
p=[]
for i in a:
  if i>0:p+=[i]
  elif i<0:m+=[i]
p=sorted(p)
m=sorted(m)[::-1]
mod=10**9+7
if not p and k%2:
  ans=1
  for i in m[:k]:
    ans*=i
    ans%=mod
  print(ans)
  exit()
s=[]
while k>1:
  if len(m)<2:
    if p:
      s+=[p.pop()]
      k-=1
    else:
      s+=[m.pop()]
      k-=1
  elif len(p)>1:
    if m[-1]*m[-2]>p[-1]*p[-2]:
      s+=[m.pop(),m.pop()]
      k-=2
    else:
      s+=[p.pop()]
      k-=1
  elif len(p)==1:
    if m[-1]*m[-2]>p[-1]:
      s+=[m.pop(),m.pop()]
      k-=2
    else:
      s+=[p.pop()]
      k-=1
  elif not p:
    s+=[m.pop()]
    k-=1
if k:
  if p:s+=[p.pop()]
  else:s+=[m.pop()]
ans=1
for i in s:
  ans*=i
  ans%=mod
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
m=[]
p=[]
for i in a:
  if i>0:p+=[i]
  elif i<0:m+=[i]
p=sorted(p)
m=sorted(m)[::-1]
mod=10**9+7
s=[]
while k>0:
  if len(m)<2:
    if p:
      s+=[p.pop()]
      k-=1
    else:
      s+=[m.pop()]
      k-=1
  elif len(p)>1:
    if m[-1]*m[-2]>p[-1]*p[-2] and k>1:
      s+=[m.pop(),m.pop()]
      k-=2
    else:
      s+=[p.pop()]
      k-=1
  elif len(p)==1:
    if m[-1]*m[-2]>p[-1] and k>1:
      s+=[m.pop(),m.pop()]
      k-=2
    else:
      s+=[p.pop()]
      k-=1
  elif not p:
    s+=[m.pop()]
    k-=1
ans=1
for i in s:
  ans*=i
  ans%=mod
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
a=sorted(list(map(int,input().split())),key=abs)[::-1]
mod=10**9+7
s=1
flag=0
if k%2 and all([i<=0 for i in a]):
  a=sorted(a,key=abs)
  flag=1
p,m=-1,-1
cnt=0
for i,j in enumerate(a[:k]):
  s*=j
  s%=mod
  if j<0:
    m=i
    cnt+=1
  else:p=i
if flag:
  print(s)
  exit()
if cnt%2:s-=mod
for i in range(k,n):
  if p!=-1:s=max(s,a[i]*s//a[p])
  if m!=-1:s=max(s,a[i]*s//a[m])
print(s%mod)

Submission status: Runtime Error

Solution code:
MOD = 10 ** 9 + 7

N, K = map(int, input().split())
A = list(map(int, input().split()))
minus = []
plus = []
for a in A:
    if a < 0:
        minus.append(a)
    else:
        plus.append(a)

ans = 1
if len(minus) == N:
    if K % 2 == 0:
        A.sort()
    else:
        A.sort(reverse=True)
    for i in range(K):
        ans = ans * A[i] % MOD
    print(ans)
    exit(0)

minus.sort()
plus.sort()

if  K % 2:
    ans *= plus.pop()

B = []

while len(minus) > 1:
    a = minus.pop()
    b = minus.pop()
    B.append(a * b)

while len(plus) > 1:
    a = plus.pop()
    b = plus.pop()
    B.append(a * b)

B.sort()

for i in range(K // 2):
    ans = ans * B.pop() % MOD

print(ans)

Submission status: Runtime Error

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
mod = 10**9+7
n,k = ma()
A = lma();A.sort(key=lambda x:abs(x),reverse=True)
#print(A)
if k==n:
    prd=1
    for a in A:prd=(prd*a)%mod
    print(prd)
    exit()

Am = [-a for a in A if a<0]
Apz = [a for a in A if a>=0]
f=0 #F:plus T :minus
if k>len(Apz):
    f=(k-len(Apz))%2
prd=1
if f:
    A.sort(key=lambda x:abs(x))
    for i in range(k):
        prd =(prd*A[i])%mod
else:
    idxp=-1
    idxm=-1
    for i in range(k):
        prd=(prd*A[i]) %mod
        if A[i]<0:
            idxm+=1
        else:
            idxp+=1
    #print(idxp,idxm)
    if idxm%2==1:
        pass
    else:
        if idxp==-1 or idxp==len(Apz)-1:
            t1 = 0
        else:
            t1 = Apz[idxp]*Apz[idxp+1]
        if idxm==-1 or idxm ==len(Am)-1:
            t2=0
        else:
            t2 = Am[idxm]*Am[idxm+1]
        if t1>t2:
            prd=1
            ip =-1
            for i in range(k):
                if A[i]>=0:
                    ip+=1
                if ip==idxp:
                    prd*=Apz[idxp+1];prd%=mod
                else:
                    prd*=A[i]
                prd%=mod
        else:
            prd=1
            im = -1
            for i in range(k):
                if A[i]<0:
                    im+=1
                if im==idxm:
                    prd*=Am[idxm+1]
                else:
                    prd*=A[i]
                prd%=mod
print(prd)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
MOD = 10**9 + 7
if K == N:
    #そのままが答え
    ans = 1
    for a in A:
        ans *= a
        ans %= MOD
    print(ans % MOD)
    exit()

# pos = [a for a in A if a > 0]
neg = [a for a in A if a < 0]
n_neg = len(neg)
if n_neg == N and K % 2 == 1:
    #負になるしかない
    A.sort(reverse=True)
    ans = 1
    for i in range(K):
        ans *= A[i]
        ans %= MOD
    print(ans % MOD)
    exit()

# 正にできる
A.sort(key=lambda x: abs(x), reverse=True)
P = 1
is_p_neg = 0
for i in range(K):
    P *= A[i]
    if A[i] < 0:
        is_p_neg = not(is_p_neg)
        P %= MOD

if not is_p_neg:
    # P >= 0なら答え
    print(P%MOD)
    exit()

ng_left = N
ng_right = N
not_ng_right = N
po_left = N
for i in range(N):
    if A[i] > 0:
        po_left = i
        break
for i in range(N):
    if A[i] < 0:
        ng_left = i
        break
for i in range(K, N):
    if A[i] >= 0:
        not_ng_right = i
        break
for i in range(K, N):
    if A[i] > 0:
        ng_right = i
        break

A += [None] # right側のポインターが初期のままかどうかを判別
x1 = A[ng_left]
y1 = A[not_ng_right]
x2 = A[po_left]
y2 = A[ng_right]
if y1 is None:
    P //= x2
    P *= y2
    P %= MOD
elif y2 is None:
    P //= x1
    P *= y1
    P %= MOD
else:
    if abs(y1*x2) < abs(y2*x1):
        P //= x2
        P *= y2
        P %= MOD
    else:
        P //= x1
        P *= y1
        P %= MOD
print(P %MOD)

Submission status: Runtime Error

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
mul = lambda x, y: x * y % MOD
div = lambda x, y: x * pow(y, MOD - 2, MOD) % MOD
from functools import reduce
def resolve():
    n, k = map(int, input().split())
    A = list(map(int, input().split()))
    A.sort(key = abs, reverse = 1)

    if all(a < 0 for a in A):
        A.sort()
        if k & 1:
            print(reduce(mul, A[-k:]))
        else:
            print(reduce(mul, A[:k]))
        return


    B = A[:k]
    C = A[k:]
    s = sum(b < 0 for b in B)
    if ~s & 1:
        print(reduce(mul, A[:k]))
        return

    res = reduce(mul, A[:k])
    p, q = max(B), min(B)
    lp, lq = max(C), min(C)
    # res * lq / p と res * lp / q
    # q * lq と p * lp のうち絶対値の大きい方
    f1 = p >= 0 and lq < 0
    f2 = lp >= 0 and q < 0

    if f1 and f2:
        if abs(q * lq) >= abs(p * lp):
            ans = div(res, p)
            ans = mul(ans, lq)
        else:
            ans = div(res, q)
            ans = mul(ans, lp)
    elif f1:
        ans = div(res, p)
        ans = mul(ans, lq)
    elif f2:
        ans = div(res, q)
        ans = mul(ans, lp)
    print(ans)
resolve()

Submission status: Runtime Error

Solution code:
x = list(input().split())
a = list((int(i) for i in input().split()))
n, k = int(x[0]), int(x[1])
#import random
import queue
#n = random.choice(range(3, 8))
#k = random.choice(range(1, n))
#a = random.choices(range(-1000000, 1000000, 1), k=n)

MOD = 10**9 + 7

# check negative mode
neg = True
for i in range(n):
    if a[i] > 0:
        neg = False
if not (neg and k%2==1): neg = False
if neg: flag = 1
else: flag = -1

res = queue.PriorityQueue()
for i in range(n): res.put((flag * abs(a[i]), a[i]))
ans = 1
ansq = []

if neg: # negative case
    for i in range (k):
        (acur, cur) =  res.get()
        ans = ans * cur
        ansq.append(ans)

else: # positive case
    sm_pos, sm_neg, lg_pos, lg_neg = MOD, MOD, 0, 0
    for i in range (k):
        (acur, cur) = res.get()
        ans = ans * cur
        ansq.append(cur)
        if cur > 0 and sm_pos > acur: sm_pos = acur
        elif cur < 0 and sm_neg > acur: sm_neg = acur
    while res.qsize() > 0:
        (acur, cur) = res.get()
        if cur > 0 and lg_pos > acur: lg_pos = acur
        elif cur < 0 and lg_neg > acur: lg_neg = acur
        if lg_pos != 0 and lg_neg != 0: break
#    print (sm_pos, sm_neg, lg_pos, lg_neg, ans)
    if ans < 0:
        if lg_neg / sm_pos > lg_pos / sm_neg:
            ans = ans * lg_neg / sm_pos
        else:
            ans = ans * lg_pos / sm_neg

print (int(ans % MOD))

Submission status: Runtime Error

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
# INF =  float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353

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

import numpy as np

x = np.argsort(list(map(lambda x: -abs(x), A)))
B = []
C = []

for xx in x:
    B.append(A[xx])
    C.append(np.sign(A[xx]))

ans = 1
s = 1
flag4 = 0

for i in range(K):
    s *= C[i]

if s < 0:
    p = np.sign(B[K-1])
    flag1 = 0
    for i in range(K-1,-1,-1):
        if C[i] == p*(-1):
            idx1 = i
            flag1 = 1
            break

    flag2 = 0
    for i in range(K,N):
        if C[i] == p*(-1):
            idx2 = i
            flag2 = 1
            break

    flag3 = 0
    if flag1 == 1:
        for i in range(K,N):
            if C[i] == p:
                idx3 = i
                flag3 = 1
                break

    if flag1 and flag2 and flag3:
        if max(abs(B[K-1])*abs(B[idx3]) <= abs(B[idx1])*abs(B[idx2])):
            B[K-1] = B[idx2]
        else:
            B[idx1] = B[idx3]
    elif flag1 and (not flag2) and flag3:
        B[idx1] = B[idx3]
    elif flag1 and flag2 and (not flag3):
        B[K-1] = B[idx2]
    elif (not flag1) and flag2:
        B[K-1] = B[idx2]
    else:
        flag4 = 1

if flag4:
    for i in range(N-1,N-K-1,-1):
        ans = (ans * (B[i] % mod)) % mod
else:
    for i in range(K):
        ans = (ans * (B[i] % mod)) % mod

print(ans % mod)

Submission status: Runtime Error

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
# INF =  float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353

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

import numpy as np

x = np.argsort(list(map(lambda x: -abs(x), A)))
B = []
C = []

for xx in x:
    B.append(A[xx])
    C.append(np.sign(A[xx]))

ans = 1
s = 1
flag4 = 0

for i in range(K):
    s *= C[i]

if s < 0:
    p = np.sign(B[K-1])
    flag1 = 0
    for i in range(K-1,-1,-1):
        if C[i] == p*(-1):
            idx1 = i
            flag1 = 1
            break

    flag2 = 0
    for i in range(K,N):
        if C[i] == p*(-1):
            idx2 = i
            flag2 = 1
            break

    if flag1 == 1:
        flag3 = 0
        for i in range(K,N):
            if C[i] == p:
                idx3 = i
                flag3 = 1
                break

    if flag1 and flag2 and flag3:
        if max(abs(B[K-1])*abs(B[idx3]) <= abs(B[idx1])*abs(B[idx2])):
            B[K-1] = B[idx2]
        else:
            B[idx1] = B[idx3]
    elif flag1 and (not flag2) and flag3:
        B[idx1] = B[idx3]
    elif flag1 and flag2 and (not flag3):
        B[K-1] = B[idx2]
    elif (not flag1) and flag2:
        B[K-1] = B[idx2]
    else:
        flag4 = 1

if flag4:
    for i in range(N-1,N-K-1,-1):
        ans = (ans * (B[i] % mod)) % mod
else:
    for i in range(K):
        ans = (ans * (B[i] % mod)) % mod

print(ans % mod)

Submission status: Runtime Error

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
# INF =  float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353



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

import numpy as np

x = np.argsort(list(map(lambda x: -abs(x), A)))
B = []
C = []

for xx in x:
    B.append(A[xx])
    C.append(np.sign(A[xx]))

ans = 1
s = 1
flag4 = 0

for i in range(K):
    s *= C[i]

if s < 0:
    p = np.sign(B[K-1])
    flag1 = 0
    for i in range(K-1,-1,-1):
        if C[i] == p*(-1):
            idx1 = i
            flag1 = 1
            break

    flag2 = 0
    for i in range(K,N):
        if C[i] == p*(-1):
            idx2 = i
            flag2 = 1
            break

    if flag1 == 1:
        flag3 = 0
        for i in range(K,N):
            if C[i] == p:
                idx3 = i
                flag3 = 1
                break

    if flag1 and flag2 and flag3:
        if max(abs(B[K-1])*abs(B[idx3]) <= abs(B[idx1])*abs(B[idx2])):
            B[K-1] = B[idx2]
        else:
            B[idx1] = B[idx3]
    elif flag1 and (not flag2) and flag3:
        B[idx1] = B[idx3]
    elif flag1 and flag2 and (not flag3):
        B[idx2] = B[idx3]
    elif (not flag1) and flag2:
        B[idx2] = B[idx3]
    else:
        flag4 = 1

if flag4:
    for i in range(N-1,N-K-1,-1):
        ans = (ans * (B[i] % mod)) % mod
else:
    for i in range(K):
        ans = (ans * (B[i] % mod)) % mod

print(ans % mod)

Submission status: Runtime Error

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter,defaultdict
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
# INF =  float("inf")
INF = 10**18
import bisect
import statistics
mod = 10**9+7
# mod = 998244353



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

import numpy as np

x = np.argsort(list(map(lambda x: -abs(x), A)))
B = []
C = []

for xx in x:
    B.append(A[xx])
    C.append(np.sign(A[xx]))

ans = 1
s = 1
flag4 = 0

for i in range(K):
    s *= C[i]

if s < 0:
    p = np.sign(A[K-1])
    flag1 = 0
    for i in range(K,-1,-1):
        if C[i] == p*(-1):
            idx1 = i
            flag1 = 1
            break

    flag2 = 0
    for i in range(K+1,N):
        if C[i] == p*(-1):
            idx2 = i
            flag2 = 1
            break

    if flag1 == 1:
        flag3 = 0
        for i in range(K+1,N):
            if C[i] == p:
                idx3 = i
                flag3 = 1
                break

    if flag1 and flag2 and flag3:
        if max(abs(B[K-1])*abs(B[idx3]) <= abs(B[idx1])*abs(B[idx2])):
            B[K-1] = B[idx2]
        else:
            B[idx1] = B[idx3]
    elif flag1 and (not flag2) and flag3:
        B[idx1] = B[idx3]
    elif flag1 and flag2 and (not flag3):
        B[idx2] = B[idx3]
    elif (not flag1) and flag2:
        B[idx2] = B[idx3]
    else:
        flag4 = 1

if flag4:
    for i in range(N-1,N-K-1,-1):
        ans = (ans * (B[i] % mod)) % mod
else:
    for i in range(K):
        ans = (ans * (B[i] % mod)) % mod

print(ans % mod)

Submission status: Runtime Error

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

MOD = 10**9+7
N, K = map(int, readline().split())
A = list(map(int, readline().split()))
posi = [(a, 0) for a in A if a >= 0]
nega = [(-a, 1) for a in A if a < 0]
B = posi + nega
B.sort(reverse = True)

if N == len(nega):
    if K & 1:
        A.sort(reverse = True)
    else:
        A.sort()
    ans = 1
    
    for i in range(K):
        ans = (ans*A[i]) % MOD  
    print(ans)
else:
    cnt = 0
    for i in range(K):
        _, s = B[i]
        cnt ^= s
    
    res, _ = map(list, zip(*B[:K]))
    if cnt:
        pf, nf, ps, ns = 0, 0, 0, 0
        for i in range(K):
            b, s = B[i]
            if s:
                nf = b
            else:
                pf = b
        
        for i in range(K, N):
            b, s = B[i]
            if s:
                ns = b
                break
        for i in range(K, N):
            b, s = B[i]
            if not s:
                ps = b
                break
        
        if ns*nf >= pf*ps:
            res.remove(pf)
            res.append(ns)
        else:
            res.remove(nf)
            res.append(ps)
        
    ans = 1
    for r in res:
        ans = (ans*r)%MOD
        
    print(ans)

Submission status: Runtime Error

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

import collections
import math
import heapq

"""
#### 入力例 ####
N, X = map(int, input().split())

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

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())
"""
N, K = map(int, input().split())
A = list(map(int, input().split()))
mod = 10**9 +7

def main():
    ans = 1
    A.sort(reverse=True)
    if N == K:
        for n in range(N):
            ans*=A[n]
        print(ans % mod)
        return
    
    M = collections.deque()
    P = collections.deque()
    for n in range(N):
        if A[n] < 0:
            M.append(A[n])
        elif 0 < A[n]:
            P.append(A[n])
    if len(P) + len(M) < K:
        return 0
    if len(P) == 0:
        if(K%2 == 1):
            for k in range(K):
                ans = ans * M.popleft() % mod
            print(ans)
            return
        else:
            for k in range(K):
                ans = ans * M.pop() % mod
            print(ans)
            return
    k = 0
    while k < K:
        if k == K-1:
            ans *= P.pop() % mod
            break
        if len(P) < 2:
            ans *= M.popleft() * M.popleft() % mod
            k+=2
        elif len(M) <2:
            ans *= P.pop() * P.pop() % mod
            k+=2
        else:
            if (P[0]*P[1] < M[-1]*M[-2]):
                ans *= M.popleft() * M.popleft() % mod
                k+=2
            else:
                ans *= P.pop() * P.pop() % mod
                k+=2
    print(ans)
    return

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

import collections
import math
import heapq

"""
#### 入力例 ####
N, X = map(int, input().split())

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

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())
"""
N, K = map(int, input().split())
A = list(map(int, input().split()))
mod = 10**9 +7

def main():
    ans = 1
    A.sort(reverse=True)
    if N == K:
        for n in range(N):
            ans*=A[n]
        print(ans % mod)
        return
    
    M = collections.deque()
    P = collections.deque()
    for n in range(N):
        if A[n] < 0:
            M.append(A[n])
        elif 0 < A[n]:
            P.append(A[n])
    if len(P) + len(M) < K:
        return 0
    if len(P) == 0:
        if(K%2 == 1):
            for k in range(K):
                ans = ans * M.popleft() % mod
            print(ans)
            return
        else:
            for k in range(K):
                ans = ans * M.pop() % mod
            print(ans)
            return
    
    k = 0
    while k < K:
        p_stock = 0
        m_stock = 0
        if not len(M) < 2:
            m_stock = M[-1]*M[-2]
        if not len(P) < 2:
            p_stock = P[0]*P[1]
        if len(S) == K-1 or m_stock < p_stock:
            if not len(P) < 1:
                ans = ans * P.pop() % mod
                k+= 1
            else:
                ans = ans * M.pop() * M.pop() % mod
                k+=2
        else:
            if not len(M) < 2:
                ans = ans * M.pop() * M.pop() % mod
                k+=2
            else:
                ans = ans * P.pop() % mod
                k+= 1
    print(ans)
    return

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

import collections
import math
import heapq

"""
#### 入力例 ####
N, X = map(int, input().split())

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

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())
"""
N, K = map(int, input().split())
A = list(map(int, input().split()))
mod = 10**9 +7

def main():
    ans = 1
    A.sort(reverse=True)
    if N == K:
        for n in range(N):
            ans*=A[n]
        print(ans % mod)
        return
    
    M = collections.deque()
    P = collections.deque()
    for n in range(N):
        if A[n] < 0:
            M.append(A[n])
        elif 0 < A[n]:
            P.append(A[n])
    if len(P) + len(M) < K:
        return 0
    if len(P) == 0:
        if(K%2 == 1):
            for k in range(K):
                ans = ans * M.popleft() % mod
            print(ans)
            return
        else:
            for k in range(K):
                ans = ans * M.pop() % mod
            print(ans)
            return
    
    
    S = collections.deque()
    while len(S) != K:
        p_stock = 0
        m_stock = 0
        if len(P) < 2:
            m_stock = M[-1]*M[-2]
        if len(M) < 2:
            p_stock = P[0]*P[1]
        if len(S) == K-1 or m_stock < p_stock:
            if not len(P) < 1:
                S.append(P.pop())
        else:
            if not len(M) < 2:
                S.append(M.pop())
                S.append(M.pop())
    while len(S) != 0:
        ans = ans * S.pop() % mod
    print(ans)
    return

if __name__ == '__main__':
    main()