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:
# -*- coding: utf-8 -*-

import bisect
import copy
import collections
import heapq
import itertools
import math
import numpy as np
from operator import itemgetter
import scipy.misc
import sys

"""
#### 入力例 ####
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()))

def main():
    A.sort(reverse=True)
    M = []
    P = []
    cnt_0 = 0
    for n, a in enumerate(A):
        if 0 < a:
            P.append(a)
        elif a == 0:
            cnt_0 += 1
        else:
            M.append(a)
    M.sort(reverse=False)
    #print(P)
    #print(M)

    g_p = collections.deque()
    g_m = collections.deque()
    for n in range(0, len(P), 2):
        if n == len(P)-1 and len(P)%2 == 1:
            g_p.append((P[n], 1, P[n], 1))
            continue
        g_p.append((P[n]*P[n+1], 2, P[n], P[n+1]))
    for n in range(0, len(M), 2):
        if n == len(M)-1 and len(M)%2 == 1:
            g_m.append((M[n], 1, M[n], -1))
            continue
        g_m.append((M[n]*M[n+1], 2, M[n+1], M[n]))

    ans = 1
    hp = K
    while 2 <= hp:
        if g_p and g_m:
            if g_p >= g_m:
                hp -= g_p[0][1]
                ans *= g_p.popleft()[0]
            else:
                hp -= g_m[0][1]
                ans *= g_m.popleft()[0]
            continue
        elif not g_m:
            hp -= g_p[0][1]
            ans *= g_p.popleft()[0]
            continue
        elif not g_p:
            hp -= g_m[0][1]
            ans *= g_m.popleft()[0]
            continue
        else:
            ans *= 0    
            break

    if hp == 1:
        if g_p:
            ans*= g_p.popleft()[2]
        elif 0 < cnt_0:
            ans *= 0
        else:
            #print(ans, g_m[0])
            ans*= g_m.popleft()[2]
    mod = 10**9 +7
    print(ans%mod)
    return
    

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
a.sort(reverse = True)
w = 10**9 + 7
ans = 1
if k%2 == 1:
  for i in range(k):
    ans *= a[i]
    print(ans % w)

else:
  if n%2 == 0:
    a_new = [a[2*i]*a[2*i+1] for i in range(n//2)]
    a_new.sort(reverse = True)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)
      
  else:
    a_plus = heapq.nlargest(k, a)
    a_minus = heapq.nsmallest(k, a)
    a_plus.sort(reverse = True)
    a_minus.sort()
    a_plus_new = [a_plus[2*i]*a_plus[2*i+1] for i in range(len(a_plus))]
    a_minus_new = [a_minus[2*i]*a_minus[2*i+1] for i in range(len(a_minus))]
    a_new = a_plus_new + a_minus_new
    a_new.sort(revserse = True)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)

Submission status: Runtime Error

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
a.sort(reverse = True)
w = 10**9 + 7
ans = 1
if k%2 == 1:
  for i in range(k):
    ans *= a[i]
    print(ans % w)

else:
  if n%2 == 0:
    a_new = [a[2*i]*a[2*i+1] for i in range(n//2)]
    a_new.sort(reverse = True)
    print(a_new)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)
      
  else:
    a_plus = heapq.nlargest(k, a)
    a_minus = heapq.nsmallest(k, a)
    a_plus.sort(reverse = True)
    a_minus.sort()
    a_plus_new = [a_plus[2*i]*a_plus[2*i+1] for i in range(len(a_plus))]
    a_minus_new = [a_minus[2*i]*a_minus[2*i+1] for i in range(len(a_minus))]
    a_new = a_plus_new + a_minus_new
    a_new.sort(revserse = True)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)

Submission status: Runtime Error

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
a.sort(reverse = True)
print(a)
w = 10**9 + 7
ans = 1
if k%2 == 1:
  for i in range(k-1):
    ans *= a[i]
    print(ans % w)

else:
  if n%2 == 0:
    a_new = [a[2*i]*a[2*i+1] for i in range(n//2)]
    a_new.sort(reverse = True)
    print(a_new)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)
      
  else:
    a_plus = heapq.nlargest(k, a)
    a_minus = heapq.nsmallest(k, a)
    a_plus.sort(reverse = True)
    a_minus.sort()
    a_plus_new = [a_plus[2*i]*a_plus[2*i+1] for i in range(len(a_plus))]
    a_minus_new = [a_minus[2*i]*a_minus[2*i+1] for i in range(len(a_minus))]
    a_new = a_plus_new + a_minus_new
    a_new.sort(revserse = True)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)

Submission status: Runtime Error

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
a.sort(reverse = True)
print(a)
w = 10**9 + 7
ans = 1
if k%2 == 1:
  for i in range(k):
    ans *= a[i]
    print(ans % w)

else:
  if n%2 == 0:
    a_new = [a[2*i]*a[2*i+1] for i in range(n//2)]
    a_new.sort(reverse = True)
    print(a_new)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)
      
  else:
    a_plus = heapq.nlargest(k, a)
    a_minus = heapq.nsmallest(k, a)
    a_plus.sort(reverse = True)
    a_minus.sort()
    a_plus_new = [a_plus[2*i]*a_plus[2*i+1] for i in range(len(a_plus))]
    a_minus_new = [a_minus[2*i]*a_minus[2*i+1] for i in range(len(a_minus))]
    a_new = a_plus_new + a_minus_new
    a_new.sort(revserse = True)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)

Submission status: Runtime Error

Solution code:
import itertools
import heapq
import sys
import functools
import operator
import numpy as np
input = sys.stdin.readline
#-------------
n,k = map(int,input().split())
a = list(map(int,input().split()))
#-------------
a.sort(reverse = True)
print(a)
w = 10**9 + 7
ans = 1
if k%2 == 1:
  for i in range(k):
    ans *= a[i]
    print(ans % w)

else:
  if n%2 == 0:
    a_new = [a[2*i]*a[2*i+1] for i in range(n//2)]
    a_new.sort(reverse = True)
    print(a_new)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)
      
  else:
    a_plus = heapq.nlargest(k, a)
    a_minus = heapq.nsmallest(k, a)
    a_plus.sort(reverse = True)
    a_minus.sort()
    a_plus_new = [a_plus[2*i]*a_plus[2*i+1] for i in range(k//2)]
    a_minus_new = [a_minus[2*i]*a_minus[2*i+1] for i in range(k//2)]
    a_new = a_plus_new + a_minus_new
    a_new.sort(revserse = True)
    for j in range(k//2):
      ans *= a_new[j]
      print(ans % w)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
a = sorted(map(int, input().split()))

MOD = 10**9+7

def f(n, k, a):
  if k == 1:
    return a[n-1]
  
  res = 1
  if a[-1] < 0 and k&1:
    for i in range(1, k+1):
      res *= a[-i]
      res %= MOD
    return res
  
  left, right = 0, n-1
  fl, fr = a[left]*a[left+1], a[right]*a[right-1]
  for i in range(k//2):
    if fl>=fr:
      res *= fl
      res %= MOD
      left += 2
      fl = a[left]*a[left+1]
    else:
      res *= fr
      res %= MOD
      right -= 2
      fr = a[right]*a[right-1]
  if k&1:
    res *= a[right]
    res %= MOD
  return res

print(f(n, k, a))

Submission status: Runtime Error

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

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

plus, minus = [], []
for a in A:
    if a >= 0:
        plus.append(a)
    else:
        minus.append(a)

plus.sort(reverse=True)
minus.sort()

if not plus:
    ans = 1
    if K % 2:
        # 答えは負値になるので絶対値小さいのを取る
        for x in minus[-K:]:
            ans = (ans * x) % MOD
    else:
        # 答えは非負値になるので絶対値大きいのを取る
        for x in minus[:K]:
            ans = (ans * x) % MOD
    print(ans)
    exit()

idx = 0
for i in range(2, N, 2):
    if not len(plus) >= K - i + 2:
        idx += 2
        continue
    if len(minus) >= i:
        if minus[i - 2] * minus[i - 1] < plus[K - i + 1] * plus[K - i]:
            break
        else:
            idx += 2

ans = 1
for x in minus[:idx] + plus[:K - idx]:
    ans = (ans * x) % MOD
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
plus, minus = [], []
MOD = 10 ** 9 + 7
for a in map(int, input().split()):
    if a >= 0:
        plus.append(a)
    else:
        minus.append(a)

plus.sort(reverse=True)
minus.sort()

if not plus:
    # 負値覚悟で取る
    ans = 1
    for x in minus[-K:]:
        ans = (ans * x) % MOD
    print(ans)
    exit()

idx = 0
for i in range(2, N, 2):
    if not len(plus) >= K - i + 2:
        idx += 2
        continue
    if len(minus) >= i:
        if minus[i - 2] * minus[i - 1] < plus[K - i + 1] * plus[K - i]:
            break
        else:
            idx += 2

ans = 1
for x in minus[:idx] + plus[:K - idx]:
    ans = (ans * x) % MOD
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
import sys
count = 0
for line in sys.stdin:
    if count == 0:
        n,k = line.strip().split()
    else:
        str_number_lst = line.strip().split()
    count += 1

k = int(k)
n = int(n)
number_lst = [int(i) for i in str_number_lst]
number_lst.sort()
if number_lst[-1] <= 0:
    q = 1
    for i in range(k):
        q *= number_lst[-1-i]
    print(q)
else:
    array = deque(number_lst)
    P = 1
    left = 0
    right = len(number_lst) - 1
    for _ in range(k):
        if abs(array[left]) <= abs(array[right]):
            P = P * array[right]
            right -= 1
        else:
            P = P * array[left]
            left += 1
    if P < 0 and k != n:
        max1 = max(abs(array[right]/array[left-1]),abs(array[right+1]/array[left]))
        P *= max1 * (-1)
        print(int(P))
    else:
        print(P)

Submission status: Runtime Error

Solution code:
MOD = 10**9 + 7

def prod(a):
    res = 1
    for x in a:
        res = (res * x) % MOD
    return res

def solve(n, k, a):
    if k == 1:
        return max(a)
    elif k == n:
        return prod(a)
    elif max(a) < 0:
        a = sorted(a, reverse=True)
        return prod(a[:k])
    else:
        a = sorted(a, key=lambda x: -abs(x))
        num_negative = len(list(filter(lambda x: x < 0, a[:k])))
        if num_negative % 2 == 0:
            return prod(a[:k])
        else:
            i1, j1 = 0, n-1
            for i in range(k):
                if a[i] < 0:
                    i1 = i
            for j in range(k,n):
                if a[j] >= 0:
                    j1 = j
                    break
            i2, j2 = 0, n-1
            for i in range(k):
                if a[i] >= 0:
                    i2 = i
            for j in range(k, n):
                if a[j] < 0:
                    j2 = j
                    break
            if abs(a[j1] * a[i2]) > abs(a[i1] * b[j2]):
                return prod(a[:k]) # prod(a[:i1] + a[i1+1:k] + [a[j1]])
            else:
                return prod(a[:k]) # prod(a[:i2] + a[i2+1:k] + [a[j2]])

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

Submission status: Runtime Error

Solution code:
MOD = 10**9 + 7

def prod(a):
    res = 1
    for x in a:
        res = (res * x) % MOD
    return res

def solve(n, k, a):
    if k == 1:
        return max(a)
    elif k == n:
        return prod(a)
    elif max(a) < 0:
        a = sorted(a, reverse=True)
        return prod(a[:k])
    else:
        a = sorted(a, key=lambda x: -abs(x))
        num_negative = len(list(filter(lambda x: x < 0, a[:k])))
        if num_negative % 2 == 0:
            return prod(a[:k])
        else:
            i1, j1 = 0, n-1
            for i in range(k):
                if a[i] < 0:
                    i1 = i
            for j in range(k,n):
                if a[j] >= 0:
                    j1 = j
                    break
            i2, j2 = 0, n-1
            for i in range(k):
                if a[i] >= 0:
                    i2 = i
            for j in range(k, n):
                if a[j] < 0:
                    j2 = j
                    break
            if abs(a[j1] * a[i2]) > abs(a[i1] * b[j2]):
                return prod(a[:i1] + a[i1+1:k] + [a[j1]])
            else:
                return prod(a[:i2] + a[i2+1:k] + [a[j2]])

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

Submission status: Runtime Error

Solution code:
MOD = 10**9 + 7

def prod(a):
    res = 1
    for x in a:
        res = (res * x) % MOD
    return res

def solve(n, k, a):
    if k == 1:
        return max(a)
    elif k == n:
        return prod(a)
    elif max(a) < 0:
        a = sorted(a, reverse=True)
        return prod(a[:k])
    else:
        a = sorted(a, key=lambda x: -abs(x))
        num_negative = len(list(filter(lambda x: x < 0, a[:k])))
        if num_negative % 2 == 0:
            return prod(a[:k])
        else:
            i1, j1 = None, None
            for i in range(k):
                if a[i] < 0:
                    i1 = i
            for j in range(k,n):
                if a[j] >= 0:
                    j1 = j
                    break
            i2, j2 = None, None
            for i in range(k):
                if a[i] >= 0:
                    i2 = i
            for j in range(k, n):
                if a[j] < 0:
                    j2 = j
                    break
            if ((i1 is None) or (j1 is None)) and ((i2 is None) or (j2 is None)):
                return prod(a[:k])
            elif (i1 is None) or (j1 is None):
                return prod(a[:i2] + a[i2+1:k] + [a[j2]])
            elif (i2 is None) or (j2 is None):
                return prod(a[:i1] + a[i1+1:k] + [a[j1]])
            elif abs(a[j1] * a[i2]) > abs(a[i1] * b[j2]):
                return prod(a[:i1] + a[i1+1:k] + [a[j1]])
            else:
                return prod(a[:i2] + a[i2+1:k] + [a[j2]])

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

Submission status: Runtime Error

Solution code:
MOD = 10**9 + 7

def prod(a):
    res = 1
    for x in a:
        res = (res * x) % MOD
    return res

def solve(n, k, a):
    if k == 1:
        return max(a)
    elif k == n:
        return prod(a)
    elif max(a) < 0:
        a = sorted(a, reverse=True)
        return prod(a[:k])
    else:
        a = sorted(a, key=lambda x: -abs(x))
        num_negative = len(list(filter(lambda x: x < 0, a[:k])))
        if num_negative % 2 == 0:
            return prod(a[:k])
        else:
            i1, j1 = None, None
            for i in range(k):
                if a[i] < 0:
                    i1 = i
            for j in range(k,n):
                if a[j] >= 0:
                    j1 = j
                    break
            i2, j2 = None, None
            for i in range(k):
                if a[i] >= 0:
                    i2 = i
            for j in range(k, n):
                if a[j] < 0:
                    j2 = j
                    break
            if (i1 is None) or (j1 is None):
                return prod(a[:i2] + a[i2+1:k] + [a[j2]])
            elif (i2 is None) or (j2 is None):
                return prod(a[:i1] + a[i1+1:k] + [a[j1]])
            elif (i1 is None) or (j1 is None) or (i2 is None) or (j2 is None):
                return prod(a[:k])
            elif abs(a[j1] * a[i2]) > abs(a[i1] * b[j2]):
                return prod(a[:i1] + a[i1+1:k] + [a[j1]])
            else:
                return prod(a[:i2] + a[i2+1:k] + [a[j2]])

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

Submission status: Runtime Error

Solution code:
MOD = 10**9 + 7

def prod(a):
    res = 1
    for x in a:
        res = (res * x) % MOD
    return res

def solve(n, k, a):
    if k == 1:
        return max(a)
    elif k == n:
        return prod(a)
    elif max(a) < 0:
        a = sorted(a, reverse=True)
        return prod(a[:k])
    else:
        a = sorted(a, key=lambda x: -abs(x))
        num_negative = len(list(filter(lambda x: x < 0, a[:k])))
        if num_negative % 2 == 0:
            return prod(a[:k])
        else:
            i1, j1 = None, None
            for i in range(k):
                if a[i] < 0:
                    i1 = i
            for j in range(k,n):
                if a[j] >= 0:
                    j1 = j
                    break
            i2, j2 = None, None
            for i in range(k):
                if a[i] >= 0:
                    i2 = i
            for j in range(k, n):
                if a[j] < 0:
                    j2 = j
                    break
            if (i1 is None) or (j1 is None):
                return prod(a[:i2] + a[i2+1:k] + [a[j2]])
            elif (i2 is None) or (j2 is None):
                return prod(a[:i1] + a[i1+1:k] + [a[j1]])
            elif abs(a[j1] * a[i2]) > abs(a[i1] * b[j2]):
                return prod(a[:i1] + a[i1+1:k] + [a[j1]])
            else:
                return prod(a[:i2] + a[i2+1:k] + [a[j2]])

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

Submission status: Runtime Error

Solution code:
MOD = 10**9 + 7

def prod(a):
    res = 1
    for x in a:
        res = (res * x) % MOD
    return res

def solve(n, k, a):
    if k == 1:
        return max(a)
    elif k == n:
        return prod(a)
    elif max(a) < 0:
        a = sorted(a, reverse=True)
        return prod(a[:k])
    else:
        a = sorted(a, key=lambda x: -abs(x))
        num_negative = len(list(filter(lambda x: x < 0, a[:k])))
        if num_negative % 2 == 0:
            return prod(a[:k])
        else:
            i1, j1 = None, None
            for i in range(k):
                if a[i] < 0:
                    i1 = i
            for j in range(k,n):
                if a[j] >= 0:
                    j1 = j
                    break
            i2, j2 = None, None
            for i in range(k):
                if a[i] >= 0:
                    i2 = i
            for j in range(k, n):
                if a[j] < 0:
                    j2 = j
                    break
            if abs(a[j1] * a[i2]) > abs(a[i1] * b[j2]):
                return prod(a[:i1] + a[i1+1:k] + [a[j1]])
            else:
                return prod(a[:i2] + a[i2+1:k] + [a[j2]])

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

Submission status: Runtime Error

Solution code:
import numpy as np

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

plus = []
minus = []
zero = []
for i in range(n):
    sign = np.sign(A[i])
    if sign == 1:
        plus.append(A[i])
    elif sign == -1:
        minus.append(A[i])
    else:
        zero.append(A[i])

plus.sort()
minus.sort()
product = 1
flag_minus = False
for i in range(k):
    if flag_minus or not plus:
        product *= minus.pop()
        flag_minus = False
    elif k - i < 2 or not minus:
        product *= plus.pop()
    elif plen := len(plus) < 2 or len(minus) < 2:
        if plen < 2:
            product *= minus.pop()
            flag_minus = True
        else:
            for j in range(k - i):
                product *= plus.pop()
            break
    elif plus[-1] * plus[-2] < minus[-1] * minus[-2]:
        product *= minus.pop()
        flag_minus = True
    else:
        product *= plus.pop()
print(product % mod)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
# input
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n, k = map(int, input().split())
a = list(map(int, input().split()))
bigger_zero = [a[i] for i in a if a[i] > 0]
small_as_zero = [a[i] for i in a if a[i] <= 0]
bigger_zero.sort()
small_as_zero.sort()
# 全て0以下の時
mod = 10 ** 9 + 7
ans = 1
if len(small_as_zero) == n:
    if k % 2:
        # a[-1]から順番にかけていく
        for i in range(k):
            ans *= small_as_zero[-i - 1]
            ans %= mod
    else:
        # a[0]から
        for i in range(k):
            ans *= small_as_zero[i]
            ans %= mod
elif n ==k:
    for i in range(n):
        ans *= a[i]
        ans %= mod
else:
    plus_idx = n - 1
    if k % 2:
        ans *= bigger_zero[-1]
        plus_idx -= 1
    minus_idx = 0
    while n > 0:
        if (
            bigger_zero[plus_idx] * bigger_zero[plus_idx - 1]
            > small_as_zero[minus_idx] * small_as_zero[minus_idx + 1]
        ):
            ans *= bigger_zero[plus_idx] * bigger_zero[plus_idx - 1]
            ans %= mod
            plus_idx += 2
        else:
            ans *= small_as_zero[minus_idx] * small_as_zero[minus_idx + 1]
            ans %= mod
            minus_idx += 2
        n -= 2

Submission status: Runtime Error

Solution code:
import functools

def multiply(x, y):
  mod = pow(10,9) + 7
  ans = x * y
  if ans >= mod or ans < 0:
    ans %= mod
  return ans

n, k = map(int, input().split())
num = list(map(int, input().split()))
sort_num = sorted(num, reverse=True)
abssort_num = sorted(num, key = abs, reverse=True)
minusNum = 0
cnt = 0
answer = 1
mod = pow(10,9) + 7
flg = -1
minusCnt = 0
delFlg = 0
if (sort_num[0] < 0) and (k % 2 == 1):
  combi = abssort_num[-k:]
  answer = functools.reduce(multiply, combi)
elif k == n:
  answer = functools.reduce(multiply, num)
else:
  for i in range(n):
    if abssort_num[i] < 0:
      minusCnt += 1
      flg = i
  if minusCnt != 0:
    if (minusCnt % 2) == 1:
      del abssort_num[flg]
      n -= 1
  for i in range(n):
    if cnt == k:
      break
    if cnt == k - 1:
      if minusNum % 2 == 0:
        if abssort_num[i] > 0:
          answer *= abssort_num[i]
          answer %= mod
          break
        else:
          continue
      else:
        if abssort_num[i] < 0:
          answer *= abssort_num[i]
          answer %= mod
          break
        else:
          continue
    else:
      answer *= abssort_num[i]
      answer %= mod
      cnt += 1
      if abssort_num[i] < 0:
        minusNum += 1
  delNum = []
  for i in range(n):
      if abssort_num[i] < 0:
          delNum.append(i)
          n -= 1
  for i in delNum:
      del abssort_num[i]
  if n >= k:
      combi = abssort_num[:k]
      if functools.reduce(multiply, combi) > answer:
          answer = functools.reduce(multiply, combi)
print(answer)

Submission status: Runtime Error

Solution code:
import functools

def multiply(x, y):
  mod = pow(10,9) + 7
  ans = x * y
  if ans >= mod or ans < 0:
    ans %= mod
  return ans

n, k = map(int, input().split())
num = list(map(int, input().split()))
sort_num = sorted(num, reverse=True)
abssort_num = sorted(num, key = abs, reverse=True)
minusNum = 0
cnt = 0
answer = 1
mod = pow(10,9) + 7
flg = -1
minusCnt = 0
if (sort_num[0] < 0) and (k % 2 == 1):
  combi = abssort_num[-k:]
  answer = functools.reduce(multiply, combi)
elif k == n:
  answer = functools.reduce(multiply, num)
else:
  for i in range(n):
    if abssort_num[i] < 0:
      minusCnt += 1
      flg = i
  if minusCnt != 0:
    if (minusCnt % 2) == 1:
      del abssort_num[flg]
  for i in range(n):
    if cnt == k:
      break
    if cnt == k - 1:
      if minusNum % 2 == 0:
        if abssort_num[i] > 0:
          answer *= abssort_num[i]
          answer %= mod
          cnt += 1
        else:
          continue
      else:
        if abssort_num[i] < 0:
          answer *= abssort_num[i]
          answer %= mod
          cnt += 1
        else:
          continue
    else:
      answer *= abssort_num[i]
      answer %= mod
      cnt += 1
      if abssort_num[i] < 0:
        minusNum += 1
print(answer)

Submission status: Runtime Error

Solution code:
import functools

def multiply(x, y):
  mod = pow(10,9) + 7
  ans = x * y
  if ans >= mod or ans < 0:
    ans %= mod
  return ans

n, k = map(int, input().split())
num = list(map(int, input().split()))
sort_num = sorted(num, reverse=True)
abssort_num = sorted(num, key = abs, reverse=True)
minusNum = 0
cnt = 0
answer = 1
mod = pow(10,9) + 7
flg = -1
minusCnt = 0
if (sort_num[0] < 0) and (k % 2 == 1):
  combi = abssort_num[-k:]
  answer = functools.reduce(multiply, combi)
elif k == n:
  answer = functools.reduce(multiply, num)
else:
  for i in range(n):
    if abssort_num[i] < 0:
      minusCnt += 1
      flg = i
  if (minusCnt % 2) == 1:
    del abssort_num[flg]
  for i in range(n):
    if cnt == k:
      break
    if cnt == k - 1:
      if minusNum % 2 == 0:
        if abssort_num[i] > 0:
          answer *= abssort_num[i]
          answer %= mod
          cnt += 1
        else:
          continue
      else:
        if abssort_num[i] < 0:
          answer *= abssort_num[i]
          answer %= mod
          cnt += 1
        else:
          continue
    else:
      answer *= abssort_num[i]
      answer %= mod
      cnt += 1
      if abssort_num[i] < 0:
        minusNum += 1
print(answer)

Submission status: Runtime Error

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

def main():
    N, K = map(int,input().split())
    A = list(map(int,input().split()))
    MOD = 10**9+7
    nega, posi = [], []
    for num in A:
        if num > 0:
            posi.append(num)
        elif num < 0:
            nega.append(num)
    
    if K > len(posi)+len(nega):
        print(0)
    elif K == len(nega)+len(posi):
        ans = 1
        for num in A:
            ans *= num
            ans = (ans+MOD)%MOD
        print(ans)
    elif len(posi) == 0:
        if K%2 != 0:
            if 0 in A:
                print(0)
            else:
                nega.sort(reverse = True)
                ans = 1
                for i in range(K):
                    ans *= nega[i]
                print((ans+MOD)%MOD)
        else:
            nega.sort()
            ans = 1
            for i in range(K):
                ans *= nega[i]
            print((ans+MOD)%MOD)
    else:
        nega.sort()
        posi.sort(reverse = True)
        if K <= len(posi):
            ans = 1
            for i in range(K):
                ans *= posi[i]
            print((ans+MOD)%MOD)
            exit()
        cn = [1]
        cp = [1]
        for num in nega:
            cn.append(cn[-1]*num)
        for num in posi:
            cp.append(cp[-1]*num)
        ans = 0
        l = len(cp)
        for i in range(l):
            if K-i > len(cn):
                continue
            ret = cp[i]*cn[K-i]
            ans = max(ans, ret)
        print((ans+MOD)%MOD)
    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
A = sorted(A, key=abs, reverse = True)
print(A)
negative = 0
zero = 0
positive = 0
for a in A:
    if a < 0:
        negative += 1
    elif a == 0:
        zero += 1
    else:
        positive += 1
#print(negative, K)
if N == K:
    ans = 1
    for a in A:
        ans *= a
elif negative == N and K%2 == 1:
    ans = 1
    A = sorted(A, key = abs)
    for a in A[:K]:
        ans *= a
else:
    ans = 1
    B = []
    for a in A[:K]:
        ans *= a
        B.append(a)
    if ans < 0:
        num1 = B[-1]
        if num1 > 0:
            flag = 0
            for n in B:
                if n < 0:
                    flag = 1
                    num2 = n
            if flag == 1:
                flag = 0
                flag2 = 0
                for n in A[K:]:
                    if n > 0 and flag == 0:
                        anti_num1 = n
                        flag = 1
                    if n < 0 and flag2 == 0:
                        anti_num2 = n
                        flag2 = 1
                if (num1 * anti_num1) >= (num2 * anti_num2):
                    B.remove(num2)
                    B.append(anti_num1)
                else:
                    B.remove(num1)
                    B.append(anti_num2)
        if num1 < 0:
            flag = 0
            for n in B:
                if n > 0:
                    num2 = n
                    flag=1
            if flag == 1:
                flag = 0
                flag2 = 0
                for n in A[K:]:
                    if n > 0 and flag == 0:
                        anti_num2 = n
                        flag = 1
                    if n < 0 and flag2 == 0:
                        anti_num1 = n
                        flag2 = 1
                if (num1 * anti_num1) >= (num2 * anti_num2):
                    B.remove(num2)
                    B.append(anti_num1)
                else:
                    B.remove(num1)
                    B.append(anti_num2)
        ans = 1
        for a in B:
            ans *= a
mod = 10**9 +7
print(ans %mod)

Submission status: Runtime Error

Solution code:
import functools
​
def sign(x):
    if x>0:
        return 1
    elif x==0:
        return 0
    else:
        return -1
    
def multiply(x,y):
    ans = x*y
    if ans>=10**9+7:
        ans %= (10**9+7)
    return ans
​
N,K = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
​
if (A[-1]<0 and K%2==1) or K==N:
    combi = A[-K:]
    if K >1:
        answer =  functools.reduce(multiply,map(abs,combi[1:]))
        answer *= combi[0]
    else:
        answer = combi[0]
    answer %= 10**9+7
else:
    signs = 1
    i,j = 0,0
    for _ in range(K):
        if abs(A[i]) > abs(A[N-j-1]):
            signs *= sign(A[i])
            i += 1
            
        else:
            signs *= sign(A[N-j-1])
            j += 1
    combi = A[N-j:] + A[:i]
    del A[N-j:]
    del A[:i]
    combi = combi[::-1]     
       
    if signs == -1:
        if A:
            if A[0]>=0:
                del combi[0]
                combi.append(A[-1])
            elif A[0]<0 and A[-1] >0:
                if combi[0]*A[0] > combi[-1]*A[-1]:
                    del combi[-1]
                    combi.insert(0,A[0])
                else:
                    del combi[0]
                    combi.append(A[-1])
            elif A[-1] <= 0:
                del combi[-1]
                combi.insert(0,A[0]) 
        
    answer =  functools.reduce(multiply,map(abs,combi))
print(answer)