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:
from collections import deque

MOD = 10 ** 9 + 7
ans = 1

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

if n == k:
    for x in a:
        ans *= x
    print(ans % MOD)
    exit()

p = []
m = []

for x in a:
    if x >= 0:
        p.append(x)
    else:
        m.append(x)

p.sort(reverse=True)
m.sort()

pos = deque(p)
neg = deque(m)

if len(p) == 0:
    for i in range(k):
        ans *= neg[-1]
        neg.pop()
    print(ans % MOD)
    exit()

if k % 2:
    ans *= pos.popleft()
    k -= 1

while k > 0:
    if len(pos) >= 2:
        sp = pos[0] * pos[1]
    else:
        sp = 0
    
    if len(neg) >= 2:
        sn = neg[0] * neg[1]
    else:
        sn = 0
    
    if sp > sn:
        ans *= sp
        pos.popleft()
        pos.popleft()
    else:
        ans *= sn
        neg.popleft()
        neg.popleft()
    
    ans %= MOD
    k -= 2

print(ans % MOD)

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 len([1 for a in a_list if np.sign(a)==-1])%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
num[num.index(remove)]=add
ans = 1
for num in a_list[:k]:
    ans *= num
    ans %= mod
    
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque

MOD = 10 ** 9 + 7
ans = 1

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

if n == k:
    for x in a:
        ans *= x
    print(ans % MOD)
    exit()

p = []
m = []

for x in a:
    if x >= 0:
        p.append(x)
    else:
        m.append(x)

p.sort(reverse=True)
m.sort()

pos = deque(p)
neg = deque(m)

if len(p) == 0:
    for i in range(k):
        ans *= neg[-1]
        neg.pop()
    print(ans % MOD)
    exit()

if k % 2:
    ans *= pos.popleft()
    k -= 1

while k > 0:
    if len(pos) >= 2:
        sp = pos[0] * pos[1]
    else:
        sp = 0
    
    if len(neg) >= 2:
        sn = neg[0] * neg[1]
    else:
        sn = 0
    
    if sp > sn:
        ans *= sp
        pos.popleft()
        pos.popleft()
    else:
        ans *= sn:
        neg.popleft()
        neg.popleft()
    
    ans %= MOD
    k -= 2

print(ans % MOD)

Submission status: Runtime Error

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

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

p = 1
m = 0
ans = 1
cnt = 0

while cnt < K-1:
  if A[m]*A[m+1] > A[-p]*A[-p-1]:
    ans*= A[ni]*A[n+1]%mod
    m += 2
    cnt += 2
    
  else:
    ans *= A[-p]%mod
    p += 1
    cnt += 1
    
if cnt == k-1:
  ans *= A[-p]%mod
  
if A[-1]<0 and K%2 == 1:
  ans = 1
  for i in A[N-K:]:
    ans*= i%mod
    
print(ans)

Submission status: Runtime Error

Solution code:
import sys
import math
import heapq
import bisect
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res

N,K = LI()
AS=LI()
AS.sort(reverse=True)
res = 1
if AS[0] >= 0 and AS[N-1] >= 0:
    for i in range(K):
        res *= AS[i]
        res %= DVSR
elif AS[0] > 0:
    if N != K:
        # 小さい順
        AS.reverse()
        POS = bisect.bisect_left(AS, 1)
        AS1 = AS[0:POS]
        # 大きい順
        AS2 = AS[POS:N]
        AS2.reverse()

        BS = []
        for i in range(POS//2):
            BS.append((AS1[i] * AS1[i+1], 0))
        for j in range(len(AS2)//2):
            BS.append((AS2[j] * AS2[j+1], 1))
        # 大きい順
        BS.sort(reverse=True)
        numpos = 0
        res = 1
        for i in range(min(len(BS), K//2)):
            v, positive = BS[i]
            numpos += positive*2
            res *= v
            res %= DVSR
        K -= min(len(BS), K//2)*2
        # print(K)
        for i in range(numpos, numpos+K):
            res *= AS2[i]
            res %= DVSR
    else:
        for i in range(N):
            res *= AS[i]
            res %= DVSR

else: # AS[0] <= 0
    if K % 2:
        v1 = 1
        v2 = 1
        for i in range(K):
            v1 *= AS[i]
            v1 %= DVSR
        res = v1
    else:
        res = 1
        for i in range(N-K, N):
            res *= AS[i]
            res %= DVSR

print(res%DVSR)

Submission status: Runtime Error

Solution code:
#! /usr/bin/env python3

import sys
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)
MOD = pow(10, 9) + 7

N, K, *A = map(int, read().split())

if K == N:
    ans = 1
    for a in A:
        ans = ans * a % MOD
    print(ans)
    sys.exit()

A_pos = [a for a in A if a >= 0]
A_neg = [a for a in A if a < 0]

if len(A_pos) == 0:
    if K % 2 == 1:
        A_neg.sort(reverse=True)
    else:
        A_neg.sort()
    ans = 1
    for a in A_neg[:K]:
        ans = ans * a % MOD
    print(ans)
    sys.exit()

A_pos.sort()
A_neg.sort(reverse=True)
ans = 1
r = K
if r % 2 == 1:
    ans = ans * A_pos.pop() % MOD
    r -= 1

while r > 0:
    if len(A_pos) <= 1:
        ans = ans * A_neg.pop() * A_neg.pop() % MOD
    elif len(A_neg) <= 1:
        ans = ans * A_pos.pop() * A_pos.pop() % MOD

    else:
        acc_pos = A_pos[-1] * A_pos[-2]
        acc_neg = A_neg[-1] * A_neg[-2]

    if acc_pos > acc_neg:
        ans = ans * A_pos.pop() * A_pos.pop() % MOD
    else:
        ans = ans * A_neg.pop() * A_neg.pop() % MOD
    r -= 2
print(ans % MOD)

Submission status: Runtime Error

Solution code:
import sys
import math
import heapq
import bisect
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res

N,K = LI()
AS=LI()
AS.sort(reverse=True)
res = 1
if AS[0] >= 0 and AS[N-1] >= 0:
    for i in range(K):
        res *= AS[i]
        res %= DVSR
elif AS[0] > 0:
    if N != K:
        # 小さい順
        AS.reverse()
        POS = bisect.bisect_left(AS, 1)
        AS1 = AS[0:POS]
        # 大きい順
        AS2 = AS[POS:N]
        AS2.reverse()

        BS = []
        for i in range(POS//2):
            BS.append((AS1[i] * AS1[i+1], 0))
        for j in range(len(AS2)//2):
            BS.append((AS2[i] * AS2[i+1], 1))
        # 大きい順
        BS.sort(reverse=True)
        numpos = 0
        res = 1
        for i in range(min(len(BS), K//2)):
            v, positive = BS[i]
            numpos += positive*2
            res *= v
            res %= DVSR
        K -= min(len(BS), K//2)*2
        # print(K)
        for i in range(numpos, numpos+K):
            res *= AS2[i]
            res %= DVSR
    else:
        for i in range(N):
            res *= AS[i]
            res %= DVSR

else: # AS[0] <= 0
    if K % 2:
        v1 = 1
        v2 = 1
        for i in range(K):
            v1 *= AS[i]
            v1 %= DVSR
        res = v1
    else:
        res = 1
        for i in range(N-K, N):
            res *= AS[i]
            res %= DVSR

print(res%DVSR)

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%mod)
            
    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()
        
        p = 0
        m = 0
        ans = 1
        cnt = 0

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

        print(ans%mod)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = [int(x) for x in input().split()]
a.sort()
mod = 10**9 + 7
if k%2==0:
  i = 0
  left = 0
  right = n-1
  ans = 1
  while i<k:
    m1 = a[left]*a[left+1]
    m2 = a[right]*a[right-1]
    #print(m1,m2)
    if m1<m2:
      m2%=mod
      ans*=m2
      #print("r",right)
      right -=2
    else:
      m1 %= mod
      ans *= m1
      #print(left)
      left+=2
    ans %= mod
    i+=2
  print(ans)
else:
  a = [0]
  print(a[2])

Submission status: Runtime Error

Solution code:
#! /usr/bin/env python3

import sys
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)
MOD = pow(10, 9) + 7

N, K, *A = map(int, read().split())

if K == N:
    ans = 1
    for a in A:
        ans = ans * a % MOD
    print(ans)
    sys.exit()

A_pos = [a for a in A if a >= 0]
A_neg = [a for a in A if a < 0]

if len(A_pos) == 0:
    if K % 2 == 1:
        A_neg.sort(reverse=True)
    else:
        A_neg.sort()
    ans = 1
    for a in A_neg[:K]:
        ans = ans * a % MOD
    print(ans)
    sys.exit()

A_pos.sort(reverse=True)
A_neg.sort()
ans = 1
r = K
if r % 2 == 1:
    ans = ans * A_pos[0] % MOD
    A_pos = A_pos[1:]
    r -= 1

while r > 0:
    if len(A_pos) <= 1:
        ans = ans * A_neg[0] * A_neg[1] % MOD
    elif len(A_neg) <= 1:
        ans = ans * A_pos[0] * A_pos[1] % MOD

    else:
        acc_pos = A_pos[0] * A_pos[1]
        acc_neg = A_neg[0] * A_neg[1]

    if acc_pos > acc_neg:
        ans = ans * acc_pos % MOD
    else:
        ans = ans * acc_neg % MOD
    r -= 2
print(ans % MOD)

Submission status: Runtime Error

Solution code:
#! /usr/bin/env python3

import sys
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)
MOD = pow(10, 9) + 7

N, K, *A = map(int, read().split())

if K == N:
    ans = 1
    for a in A:
        ans = ans * a % MOD
    print(ans)
    sys.exit()

A_pos = [a for a in A if a >= 0]
A_neg = [a for a in A if a < 0]

if len(A_pos) == 0:
    if K % 2 == 1:
        A_neg.sort(reverse=True)
    else:
        A_neg.sort()
    ans = 1
    for a in A_neg[:K]:
        ans = ans * a % MOD
    print(ans)
    sys.exit()

A_pos.sort()
A_neg.sort(reverse=True)
ans = 1
r = K
if r % 2 == 1:
    ans = ans * A_pos[0] % MOD
    A_pos = A_pos[1:]
    r -= 1

while r > 0:
    if len(A_pos) <= 1:
        ans = ans * A_neg[0] * A_neg[1] % MOD
    elif len(A_neg) <= 1:
        ans = ans * A_pos[0] * A_pos[1] % MOD

    else:
        acc_pos = A_pos[0] * A_pos[1]
        acc_neg = A_neg[0] * A_neg[1]

    if acc_pos > acc_neg:
        ans = ans * acc_pos % MOD
    else:
        ans = ans * acc_neg % MOD
    r -= 2
print(ans % MOD)

Submission status: Runtime Error

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

list.sort(a, reverse=True)
total = 1
count_a = 0
count_b = N-1


if a[0]<0 and K%2 != 0:
	for i in range(N):
		a[i] = abs(a[i])
	list.sort(a, reverse=False)
	for i in range(K):
		total *= a[i]
		total  =total%(10**9 +7)
	total *= -1
	total  =total%(10**9 +7)
else:
	while K>0:

		if K %2 == 1:
			total += max( a[count_a], a[count_b])
			K -= 1
 			count_a += 1
		if K> 1:
			if a[count_a]*a[count_a+1] >a[count_b]*a[count_b-1]:
				total *= a[count_a] * a[count_a+1]
				total  =total%(10**9 +7)
				count_a += 2
			else:
				total *= a[count_b]*a[count_b-1]
				count_b -= 2
				total  =total%(10**9 +7)
			K-=2
		else:
			total *= max( a[count_a], a[count_b])
			total  =total%(10**9 +7)
		K -= 1
print(total)

Submission status: Runtime Error

Solution code:
N,K = (int(x) for x in input().split())
A = [int(x) for x in input().split()]

B = sorted(A, key=lambda x: abs(x), reverse=True)

score = 1
x = 0
y = 0
for j in range(K):
    score *= B[j]
    if B[j] > 0:
        x = B[j]
    elif B[j] < 0:
        y = B[j]

scoreX = 0
scoreY = 0
if score < 0:
    flg = 0
    for j in range(K,N):
        if B[j] > 0 and (not y == 0):
            scoreX = score / y * B[j]
            flg += 1
        elif B[j] < 0 and (not x == 0):
            scoreY = score / x * B[j]
            flg += 1
        elif B[j] == 0:
            scoreX = 0
            scoreY = 0
            flg = 2
        if flg == 2:
            break
    if flg == 0:
        score = 1
        A = sorted(A, key=lambda x: abs(x))
        for j in range(K):
            score *= A[j]
    else:
        score = max(scoreX,scoreY)

print(int(score % (10**9 + 7)))

Submission status: Runtime Error

Solution code:
#! /usr/bin/env python3

import sys
import numpy as np
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)
MOD = pow(10, 9) + 7

N, K, *A = map(int, read().split())

if K == N:
    ans = 1
    for a in A:
        ans *= a
        ans %= MOD
    print(ans)
    sys.exit()

A_pos = [a for a in A if a >= 0]
A_neg = [a for a in A if a < 0]

if len(A_pos) == 0:
    if K % 2 == 1:
        A = sorted(A, key=lambda x: abs(x))
    else:
        A = sorted(A, key=lambda x: -abs(x))
    ans = 1
    for a in A_neg[:K]:
        ans *= a
        ans %= MOD
    print(ans)
    sys.exit()

A_pos = sorted(A_pos, key=lambda x: -abs(x))
A_neg = sorted(A_neg, key=lambda x: -abs(x))
ans = 1
r = K
if r % 2 == 1:
    ans *= A_pos[0]
    ans %= MOD
    A_pos = A_pos[1:]
    r -= 1

while r > 0:
    if len(A_pos) <= 1:
        ans *= A_neg[0] * A_neg[1]
        ans %= MOD
    elif len(A_neg) <= 1:
        ans *= A_pos[0] * A_pos[1]
        ans %= MOD
    else:
        acc_pos = A_pos[0] * A_pos[1]
        acc_neg = A_neg[0] * A_neg[1]

    if acc_pos > acc_neg:
        ans *= acc_pos
        ans %= MOD
    else:
        ans *= acc_neg
        ans %= MOD
    r -= 2
print(ans % MOD)

Submission status: Runtime Error

Solution code:
#! /usr/bin/env python3

import sys
import numpy as np
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)
MOD = pow(10, 9) + 7

N, K, *A = map(int, read().split())

if K == N:
    ans = 1
    for a in A:
        ans *= a
        ans %= MOD
    print(ans)
    sys.exit()

A_pos = [a for a in A if a >= 0]
A_neg = [a for a in A if a < 0]

if len(A_pos) == 0:
    if K % 2 == 1:
        A = sorted(A, key=lambda x: abs(x))
    else:
        A = sorted(A, key=lambda x: -abs(x))
    ans = 1
    for a in A[:K]:
        ans *= a
        ans %= MOD
    print(ans)
    sys.exit()

A_pos = sorted(A_pos, key=lambda x: -abs(x))
A_neg = sorted(A_neg, key=lambda x: -abs(x))
ans = 1
r = K
if r % 2 == 1:
    ans *= A_pos[0]
    ans %= MOD
    A_pos = A_pos[1:]
    r -= 1

while r > 0:
    if len(A_pos) <= 1:
        ans *= A_neg[0] * A_neg[1]
        ans %= MOD
    elif len(A_neg) <= 1:
        ans *= A_pos[0] * A_pos[1]
        ans %= MOD
    else:
        acc_pos = A_pos[0] * A_pos[1]
        acc_neg = A_neg[0] * A_neg[1]

    if acc_pos > acc_neg:
        ans *= acc_pos
        ans %= MOD
    else:
        ans *= acc_neg
        ans %= MOD
    r -= 2
print(ans % MOD)

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 = sorted(list(map(int,input().split())))

p = 1
m = 0
ans = 1
cnt = 0

while cnt < K-1:
  if A[m]*A[m+1] > A[-p]*A[-p-1]:
    ans*= A[ni]*A[n+1]%mod
    m += 2
    cnt += 2
    
  else:
    ans *= A[-p]%mod
    p += 1
    cnt += 1
    
if cnt == k-1:
  ans=ans*a[-pi]%p
  
if a[-1]<0 and k%2==1:
  ans=1
  for i in a[n-k:]:
    ans=ans*i%p
print(ans)

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%mod)
            
    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()
        
        p = 0
        m = 0
        ans = 1
        cnt = 0

        while cnt <= K:
          if p+1 <= len(AP) and m+1 <= len(AP) and AM[m]*AM[m+1] > AP[p]*A[p+1]:
            ans*= A[m]*A[m+1]%mod
            m += 2
            cnt += 2
            
          else:
            ans *= AP[p]%mod
            p += 1
            cnt += 1

        print(ans%mod)

Submission status: Runtime Error

Solution code:
#! /usr/bin/env python3

import sys
import numpy as np
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)
MOD = pow(10, 9) + 7

N, K, *A = map(int, read().split())

if K == N:
    ans = 1
    for a in A:
        ans *= a
        ans %= MOD
    print(ans)
    sys.exit()

A_pos = [a for a in A if a >= 0]
A_neg = [a for a in A if a < 0]

if len(A_neg) == N:
    if K % 2 == 1:
        A = sorted(A, key=lambda x: abs(x))
    else:
        A = sorted(A, key=lambda x: -abs(x))
    ans = 1
    for a in A[:K]:
        ans *= a
        ans %= MOD
    print(ans)
    sys.exit()

A_pos = sorted(A_pos, key=lambda x: -abs(x))
A_neg = sorted(A_neg, key=lambda x: -abs(x))
ans = 1
r = K
if r % 2 == 1:
    ans *= A_pos[0]
    ans %= MOD
    A_pos = A_pos[1:]
    r -= 1

while r > 0:
    if len(A_pos) <= 1:
        ans *= A_neg[0] * A_neg[1]
        ans %= MOD
    elif len(A_neg) <= 1:
        ans *= A_pos[0] * A_pos[1]
        ans %= MOD
    else:
        acc_pos = A_pos[0] * A_pos[1]
        acc_neg = A_neg[0] * A_neg[1]

    if acc_pos > acc_neg:
        ans *= acc_pos
        ans %= MOD
    else:
        ans *= acc_neg
        ans %= MOD
    r -= 2
print(ans % MOD)

Submission status: Runtime Error

Solution code:
from bisect import bisect_left, bisect_right
from collections import deque

mod = 10 ** 9 + 7
n, k = map(int, input().split())
A = list(map(int, input().split()))
# dp = [[[0] * (2) for _ in range(k+1)]for _ in range(n+1)]
# # dp[桁][数][負数の数=1,0]

A.sort()
n_minus = bisect_left(A, 0)
n_zero = bisect_right(A, 0) - n_minus
n_plus = n - n_minus - n_zero

possible_max = min(k, n_minus)
possible_min = max(k - (n_plus + n_zero), 0)
ans = 1
if possible_max == possible_min and possible_min % 2 == 1:
    a = A[2*n]
    if k - (possible_min) > 0 and n_zero > 0:
        print(0)
        exit()
    A_plus = A[n - (n_plus) :]
    A_minus = A[:n_minus]
    A_minus.sort(reverse=True)
    # 負の数は奇数個小さい方から選ぶ
    for i in range(possible_min):
        ans *= A_minus[i]
        ans %= mod
    for i in range(k - possible_min):
        ans *= A_plus[i]
        ans %= mod
else:
    A_plus = A[n - (n_plus) :]
    A_plus.sort(reverse=True)
    AP = deque(A_plus)
    A_minus = A[:n_minus]
    AM = deque(A_minus)
    minus_num_max = min(n_minus // 2, k // 2)
    select = k - 2 * minus_num_max  # 選ばざるを得ない数
    if n_plus < select:
        print(0)
        exit()
    kouho = []
    while k > 0:
        if n_plus >= 2:
            kouho1 = AP.popleft()
            kouho2 = AP.popleft()
            plus_kouho = kouho1 * kouho2
        elif n_plus == 1:
            kouho1 = AP.popleft()
            kouho2 = 0
            plus_kouho = kouho1
        else:
            kouho1, kouho2 = 0, 0
            plus_kouho = 0

        if n_minus >= 2:
            kouho3 = AM.popleft()
            kouho4 = AM.popleft()
            minus_kouho = kouho3 * kouho4
        else:
            kouho3 = 0
            kouho4 = 0
            minus_kouho = -1
        if plus_kouho > minus_kouho:
            n_plus -= 1
            k -= 1
            ans *= kouho1
            if kouho2 > 0:
                AP.appendleft(kouho2)
            ans %= mod
            if minus_kouho > 0:
                AM.appendleft(kouho4)
                AM.appendleft(kouho3)
        else:
            k -= 2
            n_minus -= 2
            ans *= minus_kouho
            ans %= mod
            if kouho2 > 0:
                AP.appendleft(kouho2)
            if kouho1 > 0:
                AP.appendleft(kouho1)


print(ans % mod)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
#
# Author: Tetsuya Ishikawa <tiskw111@gmail.com>
# Date  : July 05, 2020
##################################################### SOURCE START #####################################################

import heapq
import collections

class HeapQueue:

    def __init__(self, xs, mode):
        if   mode == "min": self.xs = [+x for x in xs]
        elif mode == "max": self.xs = [-x for x in xs]
        else              : raise NotImplementedError("HeapQueue.__init__: mode should be 'min' or 'max'")
        heapq.heapify(xs)
        self.mode = mode

    def __len__(self):
        return len(self.xs)

    def pop(self):
        if   self.mode == "min": return heapq.heappop(self.xs)
        elif self.mode == "max": return heapq.heappop(self.xs) * (-1)

    def push(self, x):
        if   self.mode == "min": return heapq.heappush(self.xs,  x)
        elif self.mode == "max": return heapq.heappush(self.xs, -x)

    # @staticmethod
    # def __test01__():
    #     xs = HeapQueue([-3, 2, 9, -4], "min")
    #     x0 = xs.pop()
    #     x1 = xs.pop()
    #     x2 = xs.pop()
    #     x3 = xs.pop()
    #     return (x0 == -4 and x1 == -3 and x2 == 2 and x3 == 9)


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

D = int(1E9 + 7)
r = 1

if N == K:

    for a in As:
        r = (r * a) % D

if all(a >= 0 for a in As):

    As = sorted(As, reverse=True)
    for a in As[:K]:
        r = (r * a) % D

elif K % 2 == 1 and all(a < 0 for a in As):

    As = sorted(As, reverse=True)
    for a in As[:K]:
        r = (r * a) % D

elif K % 2 == 0 and all(a < 0 for a in As):

    As = sorted(As)
    for a in As[:K]:
        r = (r * a) % D

else:

    As = sorted(As, key = lambda a: abs(a), reverse=True)

    used = As[:K]
    rest = As[K:]
    num_negative_sign = sum([1 if x < 0 else 0 for x in used])

    if num_negative_sign % 2 != 0:

        used_min_pos = None
        used_min_neg = None
        for k in range(K-1, -1, -1):
            if   used_min_pos is None and used[k] >= 0: used_min_pos = k
            elif used_min_neg is None and used[k] <  0: used_min_neg = k
            if used_min_pos and used_min_neg:
                break

        rest_min_pos = None
        rest_min_neg = None
        for k in range(N-K-1, -1, -1):
            if   rest_min_pos is None and rest[k] >= 0: rest_min_pos = k
            elif rest_min_neg is None and rest[k] <  0: rest_min_neg = k
            if rest_min_pos and rest_min_neg:
                break

        if used_min_pos is None or rest_min_neg is None:
            used[used_min_neg] = rest_min_pos
        elif used_min_neg is None or rest_min_pos is None:
            used[used_min_pos] = rest_min_neg
        else:
            v1 = abs(used[used_min_pos] * rest[rest_min_neg])
            v2 = abs(used[used_min_neg] * rest[rest_min_pos])
            if v1 < v2:
                used[used_min_pos] = rest_min_neg
            else:
                used[used_min_neg] = rest_min_pos

    for a in used:
        r = (r * a) % D

print(r)

##################################################### SOURCE FINISH ####################################################
# vim: expandtab tabstop=4 shiftwidth=4 fdm=marker

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
# モジュールのインポート
import math
import numpy as np


def get_input() -> tuple:
    """
    標準入力を取得する.

    Returns:\n
        tuple: 標準入力
    """
    N, K = list(map(int, input().split()))
    A = list(map(int, input().split()))

    return N, K, A


def main(N: int, K: int, A: list) -> None:
    """
    メイン処理.

    Args:\n
        N (int): 整数
        K (int): 整数
        A (list): 整数列
    """
    # 求解処理
    A = sorted(A, reverse=True)
    ans = 0
    if (A[0] < 0) and (K % 2 == 1):
        ans = sum(A[:K])
    else:
        A = sorted(A, key=abs, reverse=True)
        ans = 1
        for k in range(K):
            ans *= A[k]
        if ans < 0:
            ans_mp = ans
            M_high = sorted([m for m in A[:K] if m < 0], key=abs)
            P_low = sorted([p for p in A[K:] if p >= 0], key=abs, reverse=True)
            if min(len(M_high), len(P_low)) > 0:
                ans_mp = ans_mp / M_high[0] * P_low[0]

            ans_pm = ans
            P_high = sorted([p for p in A[:K] if p > 0], key=abs)
            M_low = sorted([m for m in A[K:] if m <= 0], key=abs, reverse=True)
            if min(len(P_high), len(M_low)) > 0:
                ans_pm = ans_pm / P_high[0] * M_low[0]

            ans = max(ans_mp, ans_pm)
    ans %= pow(10, 9) + 7

    # 結果出力
    print(ans)


if __name__ == "__main__":
    # 標準入力を取得
    N, K, A = get_input()

    # メイン処理
    main(N, K, A)

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 False:
  print("test")
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 True:
            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)