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) .

Solution (Python):
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()



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

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

numplus = k
numminus = 0

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



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



ans = 1

if numplus >= 0 and numminus >= 0 and numminus <= len(minus):
	for i in range(numplus):
		ans = ans * plus[i] % mod
	for i in range(numminus):
		ans = ans * minus[i] % mod
else:
	"""
	これは, ansが負になる場合や, minusが1個だけの場合, minusしかない場合, plusしかない場合に使える.
	"""
	
	tmp = sorted(a, key=lambda x:-x)
	for i in range(k):
		ans = ans * tmp[i]%mod

print(ans)

Solution (Python):
MOD = 10**9 + 7
INF = 10**9 + 7


class modint():
    def __init__(self, value):
        self.value = value % MOD

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)

    def __str__(self):
        return str(self.value)

    def __repr__(self):
        return str(self.value)

    def __add__(self, other):
        return (modint(self.value + other.value) if isinstance(other, modint)
                else modint(self.value + other))

    def __sub__(self, other):
        return (modint(self.value - other.value) if isinstance(other, modint)
                else modint(self.value - other))

    def __mul__(self, other):
        return (modint(self.value * other.value) if isinstance(other, modint)
                else modint(self.value * other))

    def __truediv__(self, other):
        return (modint(self.value * pow(other.value, MOD - 2, MOD))
                if isinstance(other, modint)
                else modint(self.value * pow(other, MOD - 2, MOD)))

    def __pow__(self, other):
        return (modint(pow(self.value, other.value, MOD))
                if isinstance(other, modint)
                else modint(pow(self.value, other, MOD)))

    def __eq__(self, other):
        return (self.value == other.value if isinstance(other, modint)
                else self.value == (other % MOD))

    def __ne__(self, other):
        return (self.value == other.value if isinstance(other, modint)
                else self.value == (other % MOD))

    def __radd__(self, other):
        return (modint(other.value + self.value) if isinstance(other, modint)
                else modint(other + self.value))

    def __rsub__(self, other):
        return (modint(other.value - self.value) if isinstance(other, modint)
                else modint(other - self.value))

    def __rmul__(self, other):
        return (modint(other.value * self.value) if isinstance(other, modint)
                else modint(other * self.value))

    def __rtruediv__(self, other):
        return (modint(other.value * pow(self.value, MOD - 2, MOD))
                if isinstance(other, modint)
                else modint(other * pow(self.value, MOD - 2, MOD)))

    def __rpow__(self, other):
        return (modint(pow(other.value, self.value, MOD))
                if isinstance(other, modint)
                else modint(pow(other, self.value, MOD)))

    def modinv(self):
        return modint(pow(self.value, MOD - 2, MOD))


def main():
    N, K = (int(i) for i in input().split())
    A = [int(i) for i in input().split()]
    ans = modint(1)
    if N == K:
        for a in A:
            ans *= a
        return print(ans)
    elif all(a < 0 for a in A) and K % 2 == 1:
        A.sort(key=abs)
        for a in A[:K]:
            ans *= a
        return print(ans)
    
    A.sort(reverse=True, key=abs)
    if sum(a < 0 for a in A[:K]) % 2 == 0:
        for a in A[:K]:
            ans *= a
    else:
        ans1 = modint(1)  
        ans2 = modint(1)  
        p_remove = False
        x1 = INF
        for a in A[:K][::-1]:
            if a > 0 and not p_remove:
                p_remove = True
                x1 = a
                continue
            ans1 *= a
        n_remove = False
        x2 = INF
        for a in A[:K][::-1]:
            if a < 0 and not n_remove:
                n_remove = True
                x2 = a
                continue
            ans2 *= a
        y1 = 0  
        y2 = 0  
        for a in A[K:]:
            if y1 == 0 and a < 0:
                y1 = a
            if y2 == 0 and a > 0:
                y2 = a
            if y1 != 0 and y2 != 0:
                break
        ans1 *= y1
        ans2 *= y2
        if x1 != INF and x2 != INF:
            if abs(x2*y1) <= abs(x1*y2):
                ans = ans2
            else:
                ans = ans1
        elif x1 == INF and x2 == INF:
            
            ans = 0
        elif x1 == INF:
            
            ans = ans2
        else:
            
            ans = ans1
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
m = 10**9+7
pos = [*filter(lambda x: x>=0, A)]
neg = [*filter(lambda x: x<0, A)]
pos.sort(reverse=True)
neg.sort()

ans = 1
i,j = 0,0
while i+j < K:
    flag = True
    if i == len(pos):
        flag = False
    elif j == len(neg):
        flag = True
    elif pos[i] >= -neg[j]:
        flag = True
    else:
        flag = False

    if flag:
        ans = ans * pos[i] % m
        i += 1
    else:
        ans = ans * neg[j] % m
        j += 1

if j % 2 == 0 or N==K:
    print(ans)
elif len(pos) == 0:
    ans = 1
    for i in range(K):
        ans = ans * neg[len(neg)-1-i] % m
    print(ans)
else:
    flag2 = True
    if i == 0:
        flag2 = True
    elif j == 0:
        flag2 = False
    elif i == len(pos):
        flag2 = False
    elif j == len(neg):
        flag2 = True
    elif pos[i-1]*pos[i] > neg[j-1]*neg[j]:
        flag2 = True
    else:
        flag2 = False

    if flag2:
        ans = ans * pow(neg[j-1],m-2,m) % m
        ans = ans * pos[i] % m
    else:
        ans = ans * pow(pos[i-1],m-2,m) % m
        ans = ans * neg[j] % m
    print(ans)

Solution (Python):

def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

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

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

    Ap = [] 
    Am = [] 
    has0 = False 
    for a in A:
        if a == 0:
            has0 = True
        elif a > 0:
            Ap.append(a)
        else:
            Am.append(-a)

    
    Ap.sort(reverse=True)
    Am.sort(reverse=True)

    ip = 0
    im = 0
    lp = len(Ap)
    lm = len(Am)

    
    
    if lp + lm < K:
        print(0)
        return

    
    
    
    
    
    
    if K % 2 == 1 and lp == 0:
        
        if has0:
            print(0)
            return
        
        else:
            ans = 1
            for a in Am[-K:]:
                ans = (ans * a) % MOD
            print(MOD - ans)
            return

    
    ans = 1
    for i in range(K):
        x = None
        if ip == lp: 
            x = Am[im]
            im += 1
        elif im == lm: 
            x = Ap[ip]
            ip += 1
        
        elif Am[im] < Ap[ip]:
            x = Ap[ip]
            ip += 1
        else:
            x = Am[im]
            im += 1
        
        ans = ans * x % MOD

    
    if im % 2 == 1:
        
        

        
        if ip == lp and im == lm:
            print(0)
            return
        
        elif ip == lp:
            ans = ans * modinv(Ap[ip-1]) % MOD
            ans = ans * Am[im] % MOD
        
        
        elif im == lm or ip == 0:
            ans = ans * modinv(Am[im-1]) % MOD
            ans = ans * Ap[ip] % MOD
        
        else:
            
            ip -= 1
            ans = ans * modinv(Ap[ip]) % MOD
            im -= 1
            ans = ans * modinv(Am[im]) % MOD
            
            
            a = Ap[ip] * Ap[ip+1]
            b = Am[im] * Am[im+1]
            

            ans = ans * max(a, b) % MOD

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):

def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

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

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

    Ap = [] 
    Am = [] 
    has0 = False 
    for a in A:
        if a == 0:
            has0 = True
        elif a > 0:
            Ap.append(a)
        else:
            Am.append(-a)

    
    Ap.sort(reverse=True)
    Am.sort(reverse=True)

    ip = 0
    im = 0
    lp = len(Ap)
    lm = len(Am)

    
    
    if lp + lm < K:
        print(0)
        return

    
    
    
    
    
    
    if K % 2 == 1 and lp == 0:
        
        if has0:
            print(0)
            return
        
        else:
            ans = 1
            for a in Am[-K:]:
                ans = (ans * a) % MOD
            print(MOD - ans)
            return

    
    ans = 1
    for i in range(K):
        x = None
        if ip == lp: 
            x = Am[im]
            im += 1
        elif im == lm: 
            x = Ap[ip]
            ip += 1
        
        elif Am[im] < Ap[ip]:
            x = Ap[ip]
            ip += 1
        else:
            x = Am[im]
            im += 1
        
        ans = ans * x % MOD

    
    if im % 2 == 1:
        
        

        
        if ip == lp and im == lm:
            print(0)
            return
        
        elif ip == lp:
            ans = ans * modinv(Ap[ip-1]) % MOD
            ans = ans * Am[im] % MOD
        
        
        elif im == lm or ip == 0:
            ans = ans * modinv(Am[im-1]) % MOD
            ans = ans * Ap[ip] % MOD
        
        else:
            
            ip -= 1
            ans = ans * modinv(Ap[ip]) % MOD
            im -= 1
            ans = ans * modinv(Am[im]) % MOD
            
            
            a = Ap[ip] * Ap[ip+1]
            b = Am[im] * Am[im+1]
            

            ans = ans * max(a, b) % MOD

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
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()



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

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

numplus = k
numminus = 0

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



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



ans = 1

if numplus >= 0 and numminus >= 0 and numminus <= len(minus) and numplus <= len(plus):
	for i in range(numplus):
		ans = ans * plus[i] % mod
	for i in range(numminus):
		ans = ans * minus[i] % mod
else:
	"""
	これは, ansが負になる場合や, minusが1個だけの場合, minusしかない場合, plusしかない場合に使える.
	"""
	
	tmp = sorted(a, key=lambda x:-x)
	for i in range(k):
		ans = ans * tmp[i]%mod

print(ans)

Solution (Python):
import sys
import heapq

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    MOD = 10 ** 9 + 7

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

    ans = 1

    
    if len(plus) < K - min((K - K % 2), (len(minus) - len(minus) % 2)):
        plus = []
        minus = []
        for a in A:
            if a >= 0:
                heapq.heappush(plus, a)
            else:
                heapq.heappush(minus, -a)

        while K > 0:
            if plus:
                x = plus[0]
            else:
                x = float("inf")

            if minus:
                y = -minus[0]
            else:
                y = float("inf")

            if abs(x) <= abs(y):
                ans *= x
                if plus:
                    heapq.heappop(plus)
            else:
                ans *= y
                if minus:
                    heapq.heappop(minus)

            ans %= MOD
            K -= 1

        print(ans)

    else:
        while K > 0:
            if K >= 2 and len(minus) >= 2 and len(plus) >= 2:
                x1 = plus[0]
                x2 = plus[1]
                y1 = minus[0]
                y2 = minus[1]
                if x1 * x2 <= y1 * y2:
                    y1 = heapq.heappop(minus)
                    y2 = heapq.heappop(minus)
                    ans *= (y1 * y2)
                    ans %= MOD
                    K -= 2
                else:
                    x1 = -heapq.heappop(plus)
                    ans *= x1
                    ans %= MOD
                    K -= 1
            elif K >= 2 and len(minus) >= 2:
                y1 = heapq.heappop(minus)
                y2 = heapq.heappop(minus)
                ans *= (y1 * y2)
                ans %= MOD
                K -= 2
            else:
                x = -heapq.heappop(plus)
                ans *= x
                ans %= MOD
                K -= 1

        print(ans % MOD)


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
import sys

N,K=map(int,input().split())
A=list(map(int,input().split()))
M=10**9+7

if N==K:
    T=1
    for a in A:
        T=(T*a)%M
    print(T)
    sys.exit()
elif max(A)<0 and K%2==1:
    A.sort(reverse=True)
    T=1
    for i in range(K):
         T=(T*A[i])%M
    print(T)
    sys.exit()
    
U=list(map(lambda x:max(x,0),A))
U.sort(reverse=True)
U=deque(U)

V=list(map(lambda x:min(x,0),A))
V.sort()
V=deque(V)

T=1
Y=0
while Y<K:
    x1,x2=U[0],U[1]
    y1,y2=V[0],V[1]

    if Y==K-1 or x1*x2>=y1*y2:
        Y+=1
        T=(T*x1)%M
        _=U.popleft()
        U.append(0)
    else:
        Y+=2
        T=(T*y1*y2)%M
        _=V.popleft()
        _=V.popleft()
        V.append(0)
        V.append(0)
print(T)

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

a_p =[]
a_m =[]
for i in a:
    if i >= 0:
        a_p.append(i)
    else :
        a_m.append(i)

a_p.sort()
a_m.sort(reverse=True)


a_select =[]

if n == k:
    a_select = a
elif len(a_p) == 0 and k%2 == 1:
    for i in range(k):
        a_select.append(a_m[i])


while len(a_select) < k:
    if len(a_select) == k - 1:
        a_select.append(a_p[-1])
        break
    if len(a_p) == 1 and (k-len(a_select))%2 == 1:
        a_select.append(a_p.pop(-1))
    elif len(a_p) == 1 and (k-len(a_select))%2 == 0:
        a_select.append(a_m.pop(-1))
        a_select.append(a_m.pop(-1))
    elif len(a_p) == 0:
        a_select.append(a_m.pop(-1))
        a_select.append(a_m.pop(-1))
    elif len(a_m) <= 1:
        a_select.append(a_p.pop(-1))
    elif a_p[-1]*a_p[-2] > a_m[-1]*a_m[-2] :
        a_select.append(a_p.pop(-1))
    else:
        a_select.append(a_m.pop(-1))
        a_select.append(a_m.pop(-1))


ans = 1
for i in a_select:
    ans = ans*i % (10**9 + 7)

print(ans)

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

allm = True
for a in A:
    if a > 0:
        allm = False
        break

if N == K:
    ans = 1
    for a in A:
        ans = (ans*a) % MOD
    print(ans)
elif allm and K % 2 == 1:
    A.sort()
    A.reverse()
    ans = 1
    for a in A[:K]:
        ans = (ans*a) % MOD
    print(ans)
else:
    p, m = [], []
    for a in A:
        if a > 0:
            p.append(a)
        if a < 0:
            m.append(-a)
    p.sort(key=lambda k: -k)
    m.sort(key=lambda k: -k)

    pi, mi = 0, 0
    ans = 1

    
    if K % 2 == 1:
        pi = 1
        ans = p[0]
        K -= 1

    while K > 0:
        if K == 1:
            ans = (ans*p[pi]) % MOD
            break
        elif pi < len(p)-1 or mi < len(m)-1:
            pv, mv = 0, 0
            if pi < len(p)-1:
                pv = p[pi]*p[pi+1]
            if mi < len(m)-1:
                mv = m[mi]*m[mi+1]

            if pv > mv:
                ans = (ans*pv) % MOD
                pi += 2
            else:
                ans = (ans*mv) % MOD
                mi += 2
            K -= 2
        else:
            ans = 0
            break
    print(ans)

Solution (Python):

import sys

sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush









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))
    
    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 not plus[i] or not plus[i + 1]:
                max_ans = P[i] * M[K-i] % mod
                continue
            if plus[i+1] * plus[i] <  minus[K-i-2] * minus[K-i-1]:
                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 not plus[i+1]:
                    max_ans = 0
                    break
                if plus[i+1] * plus[i] >  minus[K-i-2] * minus[K-i-1]:
                    max_ans = P[i] * M[K - i] % mod

    print(max_ans)

if __name__ == "__main__":
    run()

Solution (Python):
N, K = map(int, input().split())
As = list(map(int, input().split()))
P = 10**9 + 7

As.sort()
dic = {-1:0, 1:0}
for a in As:
  if a < 0:
    dic[-1] += 1
  else:
    dic[1] += 1

rlt = 1
j = 0
if N == K:
  for a in As:
    rlt *= a
    rlt %= P
  while rlt < 0:
    rlt += P
elif As[N-1] < 0 and K%2 == 1:
  for i in range(1,K+1):
    rlt *= As[-i]
    rlt %= P
  while rlt < 0:
    rlt += P
else:
  s = 0
  i = 0
  j = 1
  while s < K:
    if i+1 >= dic[-1] or s+1 == K:
      rlt *= As[-j]
      rlt %= P
      j += 1
      s += 1
    elif j+1 > dic[1]:
      rlt *= As[i]*As[i+1]
      rlt %= P
      i += 2
      s += 2
    else:
      if As[i]*As[i+1] > As[-j]*As[-(j+1)]:
        rlt *= As[i]*As[i+1]
        rlt %= P
        i += 2
        s += 2
      else:
        rlt *= As[-j]
        rlt %= P
        j += 1
        s += 1
        
print(rlt)

Solution (Python):
n,k = map(int, input().split())
a = list(map(int, input().split()))
mod = 10**9+7
a1 = []
a2 = []
cnt = 0
for i in a:
    if (i >= 0):
        a1.append(i)
    else:
        a2.append(-i)
a1.sort()
a2.sort()

if (k==1):
    print(max(a)%mod)
    exit()
if (n==k):
    ans = 1
    for i in range(k):
        ans *= a[i]
        ans %= mod
    print(ans)
    exit()
if (len(a1)==0):
    if (k%2==0):
        ans = 1
        for i in range(k):
            ans *= a2.pop()
            ans %= mod
        print(ans)
        exit()
    else:
        ans = 1
        for i in range(k):
            ans *= -a2[i]
            ans %= mod
        print(ans)
        exit()
elif (len(a2)==0):
    ans = 1
    for i in range(k):
        ans *= a1.pop()
        ans %= mod
    print(ans)
    exit()

bef1 = 10**10
bef2 = 10**10
index1 = 0
index2 = 0
ans = 1
for i in range(k):
    if (len(a1)==0):
        x = a2.pop()
        ans *= x
        ans %= mod
        index2 += 1
        cnt += 1
        bef2 = x
        continue
    if (len(a2)==0 or a1[-1]>=a2[-1]):
        x = a1.pop()
        ans *= x
        ans %= mod
        index1 += 1
        bef1 = x
    else:
        x = a2.pop()
        ans *= x
        ans %= mod
        index2 += 1
        cnt += 1
        bef2 = x
if (cnt%2==1):
    if len(a1)>0 and len(a2)>0:
        if (index1==0):
            ans *= a1[-1]
            ans *= pow(bef2,mod-2,mod)
            ans %= mod
        elif (index2==0):
            ans *= a2[-1]
            ans *= pow(bef1,mod-2,mod)
            ans %= mod
        else:
            A = a1[-1]/bef2
            B = a2[-1]/bef1
            if (a1[-1]*bef1>=a2[-1]*bef2):
                ans *= a1[-1]
                ans *= pow(bef2,mod-2,mod)
                ans %= mod
            else:
                ans *= a2[-1]
                ans *= pow(bef1,mod-2,mod)
                ans %= mod
    elif (len(a1)==0):
        ans *= a2[-1]
        ans *= pow(bef1,mod-2,mod)
        ans %= mod
    else:
        ans *= a1[-1]
        ans *= pow(bef2,mod-2,mod)
        ans %= mod
if 0 in a:
    print(max(0,ans%mod))
else:
    print(ans%mod)

Solution (Python):
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()

if n==k:
    sm=1
    for x in lst:
        sm*=x
        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 ptoken==lenp:          
        out.remove(plst[ptoken-1])
        out.append(nlst[ntoken])
    elif ntoken==lenn:
        out.remove(nlst[ntoken-1])
        out.append(plst[ptoken])
    elif ptoken==0 : 
        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)

Solution (Python):
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 k == n:
    ans_lst.extend(a)

elif len(plus_zero) == 0 and (k % 2) != 0:
    for _ in range(k):
        ans_lst.append(-minus.pop())

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

ans = 1
for i in ans_lst:
    ans = (ans * i) % MOD
print(ans)

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n,k = map(int,readline().split())
a = list(map(int,readline().split()))
mod = 10**9+7

p = []
P = 0
z = False
t = 0
for i in a:
  if i > 0:
    p.append((i,1))
    P += 1
  elif i == 0:
    p.append((0,0))
    z = True
  else:
    p.append((-i,-1))

if P == 0 and k%2 == 1:
  if z:
    print(0)
  else:
    ans = 1
    p.sort()
    for i in range(k):
      ans *= -p[i][0]
      ans %= mod
    print(ans)
  exit()

p.sort(reverse=True)
mi_p = 0
ma_m = 0
c = 0

for i in range(k):
  if p[i][1] > 0:
    mi_p = i
  elif p[i][1] == 0:
    print(0)
    exit()
  else:
    ma_m = i
    c += 1
    
if c%2 == 0:
  ans = 1
  for i in range(k):
    ans *= p[i][0]
    ans %= mod
  print(ans)
elif n == k:
  ans = 1
  for i in a:
    ans *= i
    ans %= mod
  print(ans)
else:
  ma_p = 0
  mi_m = 0
  for i in range(n-k):
    L = p[k+i]
    if L[1] > 0 and ma_p == 0:
      ma_p = p[k+i][0]
    if L[1] < 0 and mi_m == 0:
      mi_m = p[k+i][0]
    if ma_p*mi_m != 0:
      break
  ans_p = 1
  ans_m = 1
  for i in range(k):
    if i == ma_m:
      ans_p *= p[i][0]
    elif i == mi_p:
      ans_m *= p[i][0]
    else:
      ans_p *= p[i][0]
      ans_m *= p[i][0]
    ans_p %= mod
    ans_m %= mod
  if k-c > 1 and mi_m*p[ma_m][0] > ma_p*p[mi_p][0]:
    print(ans_p*mi_m%mod)
  else:
    print(ans_m*ma_p%mod)

Solution (Python):
import math
import fractions
import collections
import itertools
import pprint
from collections import deque
N,K=map(int,input().split())
A=list(map(int,input().split()))
plist=[]
mlist=[]
ans=1
p=10**9+7
for i in range(N):
    if A[i]>=0:
        plist.append(A[i])
    else:
        mlist.append(A[i])
if len(plist)==0:
    if K%2==1:
        A.sort(reverse=True)
    else:
        A.sort()
    for i in range(K):
        ans=(ans*A[i])%p
    print(ans%p)
else:
    ans=1
    plist.sort(reverse=True)
    mlist.sort()
    pmap=deque()
    mmap=deque()
    if K%2==1:
        ans=plist[0]%p
        plist.pop(0)
        K=K-1
    
    for i in range(0,len(plist)-1,2):
        pmap.append(plist[i]*plist[i+1])
    for i in range(0,len(mlist)-1,2):
        mmap.append(mlist[i]*mlist[i+1])
    if len(plist)>0:
        pres=plist[len(plist)-1]
    if len(mlist)>0:
        mres=mlist[len(mlist)-1]
    
    mapnum=K//2
    
    
    for i in range(mapnum):
        if (len(pmap)>0)and(len(mmap)>0):
            pl=pmap.popleft()
            mi=mmap.popleft()
            if pl>mi:
                ans=(ans*pl)%p
                mmap.appendleft(mi)
            else:
                ans=(ans*mi)%p
                pmap.appendleft(pl)
        elif (len(pmap)==0)and(len(mmap)>0):
            mi=mmap.popleft()
            ans = (ans *mi) % p
        elif (len(mmap)==0)and(len(pmap)>0):
            pl=pmap.popleft()
            ans = (ans *pl) % p
        else:
            ans=(ans*pres*mres)%p
    print(ans)

Solution (Python):
import math
import fractions
import collections
import itertools
import pprint
from collections import deque
N,K=map(int,input().split())
A=list(map(int,input().split()))
plist=[]
mlist=[]
ans=1
p=10**9+7
for i in range(N):
    if A[i]>=0:
        plist.append(A[i])
    else:
        mlist.append(A[i])
if len(plist)==0:
    if K%2==1:
        A.sort(reverse=True)
    else:
        A.sort()
    for i in range(K):
        ans=(ans*A[i])%p
    print(ans%p)

else:
    ans=1
    plist.sort(reverse=True)
    mlist.sort()
    pmap=deque()
    mmap=deque()
    if K%2==1:
        ans=plist[0]%p
        plist.pop(0)
        K=K-1
    
    for i in range(0,len(plist)-1,2):
        pmap.append(plist[i]*plist[i+1])
    if len(plist)>0:
        pres=plist[len(plist)-1]
    if len(mlist)>0:
        mres=mlist[len(mlist)-1]
    for i in range(0,len(mlist)-1,2):
        mmap.append(mlist[i]*mlist[i+1])
    
    mapnum=K//2
    
    
    for i in range(mapnum):
        if (len(pmap)>0)and(len(mmap)>0):
            pl=pmap.popleft()
            mi=mmap.popleft()
            if pl>mi:
                ans=(ans*pl)%p
                mmap.appendleft(mi)
            else:
                ans=(ans*mi)%p
                pmap.appendleft(pl)
        elif (len(pmap)==0)and(len(mmap)>0):
            mi=mmap.popleft()
            ans = (ans *mi) % p
        elif (len(mmap)==0)and(len(pmap)>0):
            pl=pmap.popleft()
            ans = (ans *pl) % p
        else:
            ans=(ans*pres*mres)%p
    print(ans)