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 sys
n,k = map(int,input().split())
a_list = sorted(map(int,input().split()))
mod = 10**9+7
if n-k < a_list.count(0):
    print(0)
    exit()
if (sum([1 for a in a_list if np.sign(a)!=-1])==0 and k%2==1) or (k==n and k%2==1):
    a_list.sort(key = abs)
    ans = 1
    for num in a_list[:k]:
        ans *= num
        ans %= mod
    print(ans)
    exit()
else:
    a_list.sort(key = abs,reverse = True)
    add = 1
    remove = 1
    if len([a for a in a_list[:k] if np.sign(a)==-1])%2!=0:
        negative_big = [num for num in a_list[:k] if np.sign(num)==-1]
        positive_big = [num for num in a_list[:k] if np.sign(num)==1]
        negative_small = [num for num in a_list[k:] if np.sign(num)==-1]
        positive_small = [num for num in a_list[k:] if np.sign(num)!=-1]
        
        
        if len(negative_big)==0 or len(positive_small)==0:
            remove = min(positive_big)
            add = min(negative_small)
        elif len(positive_big)==0 or len(negative_small)==0:
            remove = max(negative_big)
            add = max(positive_small)
        else:
            positive_small_max = max(positive_small)
            negative_big_max = max(negative_big)
            negative_small_min = min(negative_small)
            positive_big_min = min(positive_big)
            if positive_small_max/negative_big_max < negative_small_min/positive_big_min:
                remove = negative_big_max
                add = positive_small_max
            else:
                remove = positive_big_min
                add = negative_small_min
ans = 1
for num in a_list[:k]:
    ans *= num
    ans %= mod
    
if len([a for a in a_list[:k] if np.sign(a)==-1])%2!=0:
    ans *= add
    ans %= mod
    ans *= pow(remove, mod-2, mod)
    ans %= mod

print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush
#from collections import OrderedDict, defaultdict
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
#from collections import deque
#import numba

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

    plus = [a for a in A if a >= 0]
    minus = [-a for a in A if a < 0]

    plus = sorted(plus, reverse=True)
    minus = sorted(minus, reverse=True)

    P, M  = [1], [1]
    for p in plus:
        P.append((P[-1] * p) % mod)
    for m in minus:
        M.append(((M[-1] * (-m)) % mod))
    #print(P, M)
    max_ans = -1

    for i in range(K, -1, -2):
        if len(plus) < i:continue
        if len(minus) < K - i:continue
        if max_ans == -1:
            max_ans = P[i] * M[K-i] % mod
        else:
            if plus[i+1] / minus[K-i-2] < minus[K-i-3] / plus[i]:
                max_ans = P[i] * M[K-i] % mod

    if max_ans == -1:
        plus = plus[::-1]
        minus = minus[::-1]
        P, M = [1], [1]
        for p in plus:
            P.append((P[-1] * p) % mod)
        for m in minus:
            M.append(((M[-1] * (-m)) % mod))

        for i in range(K-1, -1, -2):
            if len(plus) < i: continue
            if len(minus) < K - i: continue
            if max_ans == -1:
                max_ans = P[i] * M[K - i] % mod
            else:
                if not plus[i] or plus[i+1]:
                    max_ans = 0
                    break
                if plus[i + 1] / minus[K - i - 2] > minus[K - i - 3] / plus[i]:
                    max_ans = P[i] * M[K - i] % mod

    print(max_ans)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

n, k = map(int, input().split())
a = list(map(int, input().split()))
MOD = 10 ** 9 + 7

plus_zero = []
minus = []

for i in a:
    if i >= 0:
        plus_zero.append(i)
    if i < 0:
        minus.append(-i)

from collections import deque

plus_zero = deque(sorted(plus_zero, reverse=True))
minus = deque(sorted(minus, reverse=True))
ans_lst = []
# 負
if len(plus_zero) == 0 and (k % 2) != 0:
    for _ in range(k):
        ans_lst.append(-minus.pop())
# 正 or 0
else:
    while len(ans_lst) != k:
        if len(ans_lst) == k-1:
            ans_lst.append(plus_zero.popleft())
        else:
            if len(plus_zero) == 0:
                ans_lst.append(minus.popleft())
                ans_lst.append(minus.popleft())
                continue
            if len(plus_zero) == 1:
                if (k - len(ans_lst)) % 2 == 0:
                    ans_lst.append(minus.popleft())
                    ans_lst.append(minus.popleft())
                else:
                    ans_lst.append(plus_zero.popleft())
                continue
            if len(minus) < 2:
                ans_lst.append(plus_zero.popleft())
                continue
            if len(plus_zero) >= 2 and len(minus) >= 2:
                if (plus_zero[0] * plus_zero[1]) >= (minus[0] * minus[1]):
                    ans_lst.append(plus_zero.popleft())
                else:
                    ans_lst.append(minus.popleft())
                    ans_lst.append(minus.popleft())
                continue
# functools.reduceはTLEをくらう場合があるので気をつける
ans = 1
for i in ans_lst:
    ans = (ans * i) % MOD
print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush
#from collections import OrderedDict, defaultdict
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
#from collections import deque
#import numba

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

    plus = [a for a in A if a >= 0]
    minus = [-a for a in A if a < 0]

    plus = sorted(plus, reverse=True)
    minus = sorted(minus, reverse=True)

    P, M  = [1], [1]
    for p in plus:
        P.append((P[-1] * p) % mod)
    for m in minus:
        M.append(((M[-1] * (-m)) % mod))
    #print(P, M)
    max_ans = -1

    for i in range(K, -1, -2):
        if len(plus) < i:continue
        if len(minus) < K - i:continue
        if max_ans == -1:
            max_ans = P[i] * M[K-i] % mod
        else:
            if plus[i+1] / minus[K-i-2] < minus[K-i-3] / plus[i]:
                max_ans = P[i] * M[K-i] % mod

    if max_ans == -1:
        plus = plus[::-1]
        minus = minus[::-1]
        P, M = [1], [1]
        for p in plus:
            P.append((P[-1] * p) % mod)
        for m in minus:
            M.append(((M[-1] * (-m)) % mod))

        for i in range(K-1, -1, -2):
            if len(plus) < i: continue
            if len(minus) < K - i: continue
            if max_ans == -1:
                max_ans = P[i] * M[K - i] % mod
            else:
                if plus[i + 1] / minus[K - i - 2] > minus[K - i - 3] / plus[i]:
                    max_ans = P[i] * M[K - i] % mod

    print(max_ans)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
from functools import reduce
from operator import mul

mod = 10**9 + 7

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

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

if N == K:
    print(reduce(mul, A)%mod)

else:

    AP = []
    AM = []
    for i in A:
        if i < 0:
            AM.append(i)
        else:
            AP.append(i)
            
    if len(AP) == 0 and K%2 != 0:
        AM.sort(reverse=True)
        AM = AM[:K]
        print(reduce(mul, AM)%mod)

    else:
        
        AP.sort(reverse=True)
        AM.sort()
        
        ans = 1
        p = 0
        m = 0
        cnt = 0
        while True:
            if (K - cnt) == 1:
                ans *= AP[p]
                print(ans%mod)
                break
                
            elif 1 >= len(AP) and 2 <= len(AM):
                ans *= (AM[m]*AM[m+1])
                m += 2
                cnt += 2 
            
            elif 2 <= len(AP) and 1 >= len(AM):
                ans *= (AP[p]*AP[p+1])
                p += 2
                cnt += 2
            
            else:   
                if AP[p]*AP[p+1] >= AM[m]*AM[m+1]:
                    ans *= (AP[p]*AP[p+1])
                    p += 2
                    cnt += 2
                
                else:
                    ans *= (AM[m]*AM[m+1])
                    m += 2
                    cnt += 2 

            if cnt == K:
                print(ans%mod)
                break

Submission status: Runtime Error

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

plst=sorted([x for x in lst if x>=0],reverse=True)
nlst=sorted([abs(x) for x in lst if x<0],reverse=True)
out=[None for _ in range(k)]
lenn=len(nlst)
lenp=len(plst)



if lenp==0 and k%2==1:
    sm=1
    for i in range(lenn-1,lenn-k-1,-1):
        sm*=-nlst[i]
        sm%=mod
    print(sm)
    exit()


ptoken=0
ntoken=0
token=0
pm=0



while token<k:
    if ptoken==lenp:
        out[token]=nlst[ntoken]
        pm=(pm+1)%2
        ntoken+=1
    elif ntoken==lenn:
        out[token]=plst[ptoken]
        ptoken+=1
    elif plst[ptoken]>nlst[ntoken]:
        out[token]=plst[ptoken]
        ptoken+=1
    else :
        out[token]=nlst[ntoken]
        pm=(pm+1)%2
        ntoken+=1
    token+=1

if pm==1:
    if n!=k:
        if ptoken==lenp:          
            out.remove(plst[ptoken-1])
            out.append(nlst[ntoken])
        elif ntoken==lenn:
            out.remove(nlst[ntoken-1])
            out.append(plst[ptoken])
        else : 
            if nlst[ntoken-1]*nlst[ntoken]>=plst[ptoken-1]*plst[ptoken]:
                out.remove(plst[ptoken-1])
                out.append(nlst[ntoken])
            else :
                out.remove(nlst[ntoken-1])
                out.append(plst[ptoken])               

sm=1
for x in out:
    sm*=x
    sm%=mod

print(sm)

Submission status: Runtime Error

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

if n == k:
   for i in a:
       ans *= i
       if abs(ans) >10**9+7:
           ans = ans%(10**9+7)

elif all(i < 0 for i in a) and k%2 ==1:
    a.sort(reverse = True)
    for i in range(k):
        ans *= a[i]
        if abs(ans) > 10 ** 9 + 7:
            ans = ans % (10 ** 9 + 7)

else:
    am =[]
    ap =[]

    a.sort(key = abs,reverse = True)
    amax = a[:k]
    amin = a[k:]
    c=1
    if 0 in amax:
        ans = 0
    else:
        for i in amax:
            if i<0:
                am.append(i)
                c *=-1
            elif i>0:
                ap.append(i)
        if c ==1:
            for i in amax:
                ans *= i
                if abs(ans) > 10 ** 9 + 7:
                    ans = ans % (10 ** 9 + 7)
        else:

            if min(amin)/min(ap) > max(amin)/max(am):
                amax.remove(max(am))
                amax.append(max(amin))
            else:
                amax.remove(min(ap))
                amax.append(min(amin))
            for i in amax:
                ans *= i
                if abs(ans) > 10 ** 9 + 7:
                    ans = ans % (10 ** 9 + 7)

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

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
n,k = map(int,input().split())
a_list = sorted(map(int,input().split()))
mod = 10**9+7
if n-k < a_list.count(0):
    print(0)
    exit()
if (sum([1 for a in a_list if np.sign(a)!=-1])==0 and k%2==1) or (k==n and k%2==1):
    a_list.sort(key = abs)
    ans = 1
    for num in a_list[:k]:
        ans *= num
        ans %= mod
    print(ans)
    exit()
else:
    a_list.sort(key = abs,reverse = True)
    add = 1
    remove = 1
    if len([a for a in a_list[:k] if np.sign(a)==-1])%2!=0:
        negative_big = [num for num in a_list[:k] if np.sign(num)==-1]
        positive_big = [num for num in a_list[:k] if np.sign(num)!=1]
        negative_small = [num for num in a_list[k:] if np.sign(num)==-1]
        positive_small = [num for num in a_list[k:] if np.sign(num)!=-1]
        
        
        if len(negative_big)==0 or len(positive_small)==0:
            remove = min(positive_big)
            add = min(negative_small)
        elif len(positive_big)==0 or len(negative_small)==0:
            remove = max(negative_big)
            add = max(positive_small)
        else:
            positive_small_max = max(positive_small)
            negative_big_max = max(negative_big)
            negative_small_min = min(negative_small)
            positive_big_min = min(positive_big)
            if positive_small_max/negative_big_max < negative_small_min/positive_big_min:
                remove = negative_big_max
                add = positive_small_max
            else:
                remove = positive_big_min
                add = negative_small_min
ans = 1
for num in a_list[:k]:
    ans *= num
    ans %= mod
    
if len([a for a in a_list[:k] if np.sign(a)==-1])%2!=0:
    ans *= add
    ans %= mod
    ans *= pow(remove, mod-2, 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

plus = []
minus = []

for i in a:
	if i >= 0:
		plus.append(i)
	else:
		minus.append(i)

plus.sort(key=lambda x:-x)
minus.sort()

#print(plus, minus)

"""
貪欲チックに求める
numplus … 前からnumplus番目まで掛け合わせる
numminus … 前からnumminus番目まで掛け合わせる

入力例2に合わせるのは場合分けが必要だが, minusは2個単位で管理する.
"""
numplus = k
numminus = 0

"""
kがplusを超える場合, うまく処理ができないのでリスト参照できる範囲まで下げる.
"""
while numplus > len(plus):
	numplus -= 2
	numminus += 2

if numplus < 0:
	numminus += numplus
	ans = 1
	tmp = sorted(a, key=lambda x:-x)
	for i in range(numminus):
		ans = ans * tmp[i] % mod
	print(ans)
	exit()

#print(numplus, numminus)

tmpplus = -1
tmpminus = -1

while numplus-1 >= 0 and numminus+1 < len(minus):
	if plus[numplus-1] * plus[numplus-2] <= minus[numminus] * minus[numminus+1]:
		numplus -= 2
		numminus += 2
		tmpminus = numminus
		tmpplus = numplus
	else:
		break

#print(tmpminus, tmpplus)

ans = 1
for i in range(numplus):
	ans = ans * plus[i] % mod
for i in range(numminus):
	ans = ans * minus[i] % mod
print(ans)

Submission status: Runtime Error

Solution code:
def main():
    M=10**9+7
    n,k,*a=map(int,open(0).read().split())
    x,y=[],[]
    for i in a:
        if i>0:x+=i,
        if i<0:y+=i,
    if len(x)+len(y)<k or k%2 and not x and len(y)<n:
        print(0)
        exit()
    if k%2 and not x:
        c=1
        for i in sorted(y)[-k:]:
            c=c*i%M
        print(c)
        exit()
    x=sorted(x)[::-1][:k]
    i=len(x)
    y.sort()
    m=len(y)
    j=0
    if i<k:
        j=k-i
        if j%2:
            x=x[:-1]
            i-=1
            j+=1
        x+=y[:j]
        j+=1
    if len(x)!=k:1/0
    while i>1 and j+1<m and x[i-1]*x[i-2]<y[j]*y[j+1]:
        x[i-1],x[i-2]=y[j],y[j+1]
        i-=2
        j+=2
    c=1
    for i in x:
        c=c*i%M
    print(c)
main()

Submission status: Runtime Error

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()
A = IL()
A = sorted(A,key= lambda x:-abs(x))

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

if max(A)<0 and K%2==1:
  ans = 1
  for i in range(K):
    ans *= A[N-1-i]
    ans %= MOD
  print(ans)
  exit()

count_M = 0
last_M = None
last_P = None
for i in range(K):
  if A[i] < 0:
    last_M = i
    count_M += 1
  else:
    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,N):
      if A[i] >= 0:
        CHANGE1 = A[i]
        ans = A[i]%MOD
        for ii in range(K):
          if ii != last_M:
            ans *= A[ii]
            ans %= MOD
        ANS1 = ans
        break
  if last_P!=None:
    for i in range(K,N):
      if A[i] <= 0:
        CHANGE2 = A[i]
        ans = A[i]%MOD
        for ii in range(K):
          if ii != last_P:
            ans *= A[ii]
            ans %= MOD
        ANS2 = ans
        break
  if last_M == None:
    print(ANS2)
    exit()
  elif last_P == None:
    print(ANS1)
    exit()
  else:
    if abs(A[last_M]*CHANGE2)<abs(A[last_P]*CHANGE1):
      print(ANS1)
    else:
      print(ANS2)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())

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

A_minus = []
A_plus = []

for a in A:
    if a >= 0:
        A_plus.append(a)
    else:
        A_minus.append(a)

A_plus.sort(reverse=True)
A_minus.sort()

MOD = 10 ** 9 + 7


# aの-1乗をmで割ったときの商を求める
def mod_inv(mod_a, m=10 ** 9 + 7):
    b = m
    u = 1
    v = 0
    while b > 0:
        t = mod_a // b
        mod_a -= t * b
        c = mod_a
        mod_a = b
        b = c

        u -= t * v
        c = u
        u = v
        v = c
    u %= m
    return u


def get_all_mul(area):
    ans = 1
    for a_check in area:
        ans = mul(ans, a_check)
    return ans


def mul(mul_a, mul_b):
    return (mul_a * mul_b) % MOD


def solve():
    ans = 1

    if K == N:
        return get_all_mul(A)
    if len(A_plus) == 0 and K & 1:
        return get_all_mul(A_minus[-K:])

    A_plus.append(0)
    A_minus.append(0)

    plus_choice_num = 0
    minus_choice_num = 0
    last_plus_choice = 0
    last_minus_choice = 0

    for _ in range(K):
        if A_plus[plus_choice_num] > -A_minus[minus_choice_num]:
            ans = mul(ans, A_plus[plus_choice_num])
            last_plus_choice = A_plus[plus_choice_num]
            plus_choice_num += 1
        else:
            ans = mul(ans, A_minus[minus_choice_num])
            last_minus_choice = A_minus[minus_choice_num]
            minus_choice_num += 1

    if minus_choice_num & 1 == 0:
        return ans
    elif ans == 0:
        return ans
    else:
        if last_plus_choice * A_plus[plus_choice_num] >= last_minus_choice * A_minus[minus_choice_num]:
            change = mul(mod_inv(last_minus_choice), A_plus[plus_choice_num])
        else:
            change = mul(mod_inv(last_plus_choice), A_minus[minus_choice_num])
        return mul(ans, change)


print(solve())

Submission status: Runtime Error

Solution code:
from bisect import bisect_left
N,K=map(int, input().split())
A=list(map(int, input().split()))
p=10**9+7
A=sorted(A)
thresh=bisect_left(A,0)
minus=A[:thresh]
plus=A[thresh:][::-1]

#print(plus, minus)
if len(plus)==0:
    ans=1
    if K%2!=0:
        minus=minus[::-1]
        for i in range(K):
            ans*=minus[i]
            ans%=p
    else:
        for i in range(K):
            ans*=minus[i]
            ans%=p
    print(ans)
    exit()

if len(minus)==0:
    ans=1
    for i in range(K):
        ans*=plus[i]
        ans%=p
    print(ans)
    exit()

midx=0
pidx=0
ans=1
while K>0 and (0<=midx<len(minus) or 0<=pidx<len(plus)):
    if midx==len(minus)-1:
        nexmin=minus[midx]
    elif 0<=midx<len(minus)-1:
        nexmin=minus[midx]*minus[midx+1]
    else:
        nexmin=-1


    if pidx==len(plus)-1:
        nexplus=plus[pidx]
    elif 0<=pidx<len(plus)-1:
        
        nexplus=plus[pidx]*plus[pidx+1]
    else:
        nexplus=-float("INF")

    if nexmin>=nexplus and K>=2:
        ans*=nexmin
        ans%=p
        midx+=2
        K-=2
    else:
        ans*=plus[pidx]
        ans%=p
        pidx+=1
        K-=1

print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
sys.setrecursionlimit(10**7)
from pprint import pprint as pp
from pprint import pformat as pf
# @pysnooper.snoop()
#import pysnooper # debug

import math
#from sortedcontainers import SortedList, SortedDict, SortedSet # no in atcoder
import bisect

def list_safe_get(l, index, default=None):
    if index < len(l):
        return l[index]
    return default

class ModInt(int):

    MOD = 10 ** 9 + 7

    def __add__(self, other):
        self = ModInt(int.__add__(self, other) % ModInt.MOD)
        return self

    def __mul__(self, other):
        self = ModInt(int.__mul__(self, other) % ModInt.MOD)
        return self

def mysplit(data):
    ps = [] # include 0
    ms = []
    for d in data:
        if d < 0:
            ms.append(ModInt(d))
        else:
            ps.append(ModInt(d))
    return list(reversed(sorted(ps))), sorted(ms)

def small_abs(ms, k):
    ans = ModInt(1)
    ms = list(reversed(ms))
    for i in range(k):
        ans *= ms[i]
    return ans

def factor_all(factors):
    #print('factors') # debug
    #print(factors) # debug
    ans = ModInt(1)
    for f in factors:
        ans *= f
    return ans

def solve(data, k):
    if len(data) == k:
        ans = ModInt(1)
        for d in data:
            ans *= d
        return ans
    ps, ms = mysplit(data)
    if len(ps) == 0:
        return small_abs(ms, k)
    factors = []
    sign_p = True
    pk = 0
    mk = 0
    while k > 0:
        if pk >= len(ps):
            factors.append(ms[mk]); mk += 1; k -= 1; sign_p = not sign_p; continue
        if mk >= len(ms):
            factors.append(ps[pk]); pk += 1; k -= 1; continue
        if ps[pk] > -1 * ms[mk]:
            factors.append(ps[pk]); pk += 1; k -= 1; continue
        else:
            factors.append(ms[mk]); mk += 1; k -= 1; sign_p = not sign_p; continue
    if sign_p is False:
        cand_rm_p = ps[pk - 1]
        cand_add_m = list_safe_get(ms, mk)
        cand_rm_m = ms[mk - 1]
        cand_add_p = list_safe_get(ps, pk)
        if cand_add_m is None:
            factors.remove(cand_rm_m); factors.append(cand_add_p)
        elif cand_add_p is None:
            factors.remove(cand_rm_p); factors.append(cand_add_m)
        else:
            if cand_rm_m * cand_add_m > cand_rm_p * cand_add_p:
                factors.remove(cand_rm_p); factors.append(cand_add_m)
            else:
                factors.remove(cand_rm_m); factors.append(cand_add_p)
    return factor_all(factors)


if __name__ == '__main__':
    n, k = list(map(int, input().split()))
    data = list(map(int, input().split()))
    ans = solve(data, k)
    #print('ans') # debug
    print(ans)



    #print('\33[32m' + 'end' + '\033[0m') # debug

Submission status: Runtime Error

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

if n == k:
   for i in a:
       ans *= i
       if abs(ans) >10**9+7:
           ans = ans%(10**9+7)
elif all(i <= 0 for i in a) and k%2 ==1:
    a.sort(reverse = True)
    for i in range(k):
        ans *= a[i]
        if abs(ans) > 10 ** 9 + 7:
            ans = ans % (10 ** 9 + 7)
else:
    am =[]
    ap =[]

    a.sort(key = abs,reverse = True)
    amax = a[:k]
    amin = a[k:]
    c=1
    for i in amax:
        if i<0:
            am.append(i)
            c *=-1
        elif i>0:
            ap.append(i)
    if c ==1:
        for i in amax:
            ans *= i
            if abs(ans) > 10 ** 9 + 7:
                ans = ans % (10 ** 9 + 7)
    else:

        if min(amin)/min(ap) > max(amin)/max(am):
            amax.remove(max(am))
            amax.append(max(amin))
        else:
            amax.remove(min(ap))
            amax.append(min(amin))
        for i in amax:
            ans *= i
            if abs(ans) > 10 ** 9 + 7:
                ans = ans % (10 ** 9 + 7)

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

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())

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

A_minus = []
A_plus = []

for a in A:
    if a >= 0:
        A_plus.append(a)
    else:
        A_minus.append(a)

A_plus.sort(reverse=True)
A_minus.sort()

MOD = 10 ** 9 + 7


# aの-1乗をmで割ったときの商を求める
def mod_inv(mod_a, m=10 ** 9 + 7):
    b = m
    u = 1
    v = 0
    while b > 0:
        t = mod_a // b
        mod_a -= t * b
        c = mod_a
        mod_a = b
        b = c

        u -= t * v
        c = u
        u = v
        v = c
    u %= m
    return u


def get_all_mul(area):
    ans = 1
    for a_check in area:
        ans = mul(ans, a_check)
    return ans


def mul(mul_a, mul_b):
    return (mul_a * mul_b) % MOD


def solve():
    ans = 1

    if K == N:
        return get_all_mul(A)
    if len(A_plus) == 0 and K & 1:
        return get_all_mul(get_all_mul(A_minus[-K:]))

    A_plus.append(0)
    A_minus.append(0)

    plus_choice_num = 0
    minus_choice_num = 0
    last_plus_choice = 0
    last_minus_choice = 0

    for _ in range(K):
        if A_plus[plus_choice_num] > -A_minus[minus_choice_num]:
            ans = mul(ans, A_plus[plus_choice_num])
            last_plus_choice = A_plus[plus_choice_num]
            plus_choice_num += 1
        else:
            ans = mul(ans, A_minus[minus_choice_num])
            last_minus_choice = A_minus[minus_choice_num]
            minus_choice_num += 1

    if minus_choice_num & 1 == 0:
        return ans
    elif ans == 0:
        return ans
    else:
        if last_plus_choice * A_plus[plus_choice_num] >= last_minus_choice * A_minus[minus_choice_num]:
            change = mul(mod_inv(last_minus_choice), A_plus[plus_choice_num])
        else:
            change = mul(mod_inv(last_plus_choice), A_minus[minus_choice_num])
        return mul(ans, change)


print(solve())