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: Accepted

Solution code:
import sys

mod = 10**9+7

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

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

det = -1###Aのすべての要素が負か否か
for i in range(K):
    if A[i] >= 0:
        det = 1
        break

if det == -1 and K%2 == 1:
    value = 1
    A.sort(reverse = True)
    for i in range(K):
        value *= A[i]
        value %= mod
    print(value)
    sys.exit(0)

A.sort(key = lambda x:abs(x), reverse = True)

###
#print(A[(K-100):K])
#print(A[K:(K+100)])
###

value = 1
sgn = 1
for i in range(K):
    value *= A[i]
    value %= mod
    if A[i] < 0:
        sgn *= -1
    elif A[i] == 0:
        sgn = 0

#print(sgn,value)

if N==K:
    print(value)

elif sgn >=0:
    print(value)
else:
    ###この場合、A[0],...,A[K-1]の中に0はないと断言できることに注意

    X = ['','']###A[K-1],A[K-2],...の中にある絶対値最小の正の数、負の数の絶対値
    num = K
    while (X[0] == '' or X[1] == '') and num > 0:
        #print(A[num])
        num -= 1
        if A[num] > 0 and X[0] == '':
            X[0] = A[num]
        elif A[num] < 0 and X[1] == '':
            X[1] = A[num]
        ###
        #print(X)
        ###
    
    Y = ['','']###A[K], A[k+1],...の中にある絶対値最大の非負の数、負の数
    ###こちらでは0が登場しないとは言えない
    ###前者にだけ0を入れることでカバー
    num = K-1
    while (Y[0] == '' or Y[1] == '') and num < N-1:
        num += 1
        if A[num] > 0 and Y[0] == '':
            Y[0] = A[num]
        elif A[num] < 0 and Y[1] == '':
            Y[1] = A[num]
    
    #print(X)
    #print(Y)

    if X[0] != '' and X[1] != '' and Y[0] != '' and Y[1] != '':
        if abs(X[0]*Y[0]) >= abs(X[1]*Y[1]):
            value *= Y[0]
            value *= pow(X[1],mod-2,mod)
            value %= mod
            print(value)
        else:
            value *= Y[1]
            value *= pow(X[0],mod-2,mod)
            value %= mod
            print(value)

    elif X[1] != '' and Y[0] != '':
        value *= Y[0]
        value *= pow(X[1],mod-2,mod)
        value %= mod
        print(value)
    
    else:
        value *= Y[1]
        value *= pow(X[0],mod-2,mod)
        value %= mod
        print(value)

Submission status: Accepted

Solution code:
def prod(array):
    res = 1
    for a, _ in array:
        res *= a
        res %= MOD
    return res

MOD = 10**9 + 7
N, K = map(int, input().split())
if N==K:
    res = 1
    for a in map(int, input().split()):
        res *= a
        res %= MOD
    print(res)
    exit()
A = []
allsgn = 0
for a in map(int, input().split()):
    A.append((abs(a), a < 0))
    allsgn += a<0
A.sort(reverse=True)
sgn = 0
s0 = -1
lastA = -1
for i, p in enumerate(A[:K]):
    a, s = p
    sgn += s
    if s != s0:
        lastA = i-1
    s0 = s
lasts = s0
if allsgn==N:
    if K%2==1:
        print((-prod(A[-K:]))%MOD)
        exit()
    else:
        print(prod(A[:K])%MOD)
        exit()
if sgn%2==0:
    print(prod(A[:K])%MOD)
    exit()
if lasts != A[K][1]:
    res = prod(A[:K-1])*A[K][0]
else:
    firstA = None
    for i, p in enumerate(A[K:],start=K):
        a, s = p
        if s != lasts:
            firstA = i
            break
    if lastA == -1 or (firstA is not None and A[K][0]/A[lastA][0] < A[firstA][0]/A[K-1][0]):
        res = prod(A[:K - 1]) * A[firstA][0]
    else:
        res = prod(A[:lastA]) * prod(A[lastA + 1:K + 1])
print(res%MOD)
"""
6 3
5 -3 -3 -3 -3 -2

10 7
-10 -10 -10 -10 10 10 10 10 10 10
"""

Submission status: Accepted

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

mod=10**9+7

if A[-1]<0 and k%2==1:
    now=1
    for i in range(k):
        now*=A[-i-1]%mod
        now%=mod
    print(now)
    exit()
	
l=0
r=n-1
ans=1
if k%2==1:
    ans=A[-1]
#    print(ans)
    r-=1	
for i in range(k//2):
    mi=A[l]*A[l+1]
#    print(mi)
    pl=A[r]*A[r-1]
#    print(pl)
    if mi>pl:
        ans*= mi%mod
        ans%=mod
        l+=2
    else:
        ans*= pl%mod
        ans%=mod
        r-=2
		
print(ans%mod)

Submission status: Accepted

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

mod=10**9+7

if A[-1]<0 and k%2==1:
    now=1
    for i in range(k):
        now*=A[-i-1]%mod
        now%=mod
    print(now)
    exit()

l=0
r=n-1
ans=1
if k%2==1:
    ans=A[-1]
    r-=1

for i in range(k//2):
    mi=A[l]*A[l+1]
    pl=A[r]*A[r-1]
    if mi>pl:
        ans*= mi%mod
        ans%=mod
        l+=2
    else:
        ans*= pl%mod
        ans%=mod
        r-=2
print(ans%mod)

Submission status: Accepted

Solution code:
def modinv(a,m):
    b, u, v = m, 1, 0
    while b:
        t = a//b
        a -= t*b
        a,b = b,a
        u -= t * v
        u,v = v,u
    u %= m
    return u


n, k = map(int, input().split())
al = list(map(int, input().split()))
al_abs = []
al_p = []
al_m = []
zero_cnt = 0
MOD = 10**9+7

for a in al:
    if a == 0:
        zero_cnt+=1
    elif a > 0: 
        al_abs.append((abs(a),1))
        al_p.append(a)
    else: 
        al_abs.append((abs(a),-1))
al_abs.sort(reverse=True)


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


if len(al_abs) < k:
    print(0)
    exit()



if not al_p:
    if k%2 == 1 and zero_cnt > 0:
        print(0)
    else:
        if k%2 == 1:
            al_abs.sort()
        ans = 1
        for a,s in al_abs[:k]:
            ans *= (a*(-1))
            ans %= MOD
        print(ans)
    exit()


val = 1
m_cnt = 0
last_m = 0
last_p = 0
for i in range(k):
    v,sig = al_abs[i]
    val *= v
    val %= MOD
    if sig == -1:
        m_cnt += 1
        last_m = v
    else:
        last_p = v

if m_cnt %2 == 0:
    print(val)
    exit()


# minus -> plus 

## search next p
next_p = 0
for i in range(k,len(al_abs)):
    v,sig = al_abs[i]
    if sig == 1:
        next_p = v
        break

## search next m
next_m = 0
for i in range(k,len(al_abs)):
    v,sig = al_abs[i]
    if sig == -1:
        next_m = v
        break

if next_p == 0 and next_m == 0:
    print(0)
    exit()

# last_m -> next_p
if next_p*last_p >= next_m*last_m or last_p == 0:
    ans = val*modinv(last_m%MOD,MOD)*next_p
    ans %= MOD
    print(ans)

else:
    ans = val*modinv(last_p%MOD,MOD)*next_m
    ans %= MOD
    print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
al = list(map(int, input().split()))
al_abs = []
al_p = []
al_m = []
zero_cnt = 0
MOD = 10**9+7

for a in al:
    if a == 0:
        zero_cnt+=1
    elif a > 0: 
        al_abs.append((abs(a),1))
        al_p.append(a)
    else: 
        al_abs.append((abs(a),-1))
al_abs.sort(reverse=True)


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


if len(al_abs) < k:
    print(0)
    exit()



if not al_p:
    if k%2 == 1 and zero_cnt > 0:
        print(0)
    else:
        if k%2 == 1:
            al_abs.sort()
        ans = 1
        for a,s in al_abs[:k]:
            ans *= (a*(-1))
            ans %= MOD
        print(ans)
    exit()


val = 1
m_cnt = 0
last_m = 0
last_p = 0
for i in range(k):
    v,sig = al_abs[i]
    val *= v
    val %= MOD
    if sig == -1:
        m_cnt += 1
        last_m = v
    else:
        last_p = v

if m_cnt %2 == 0:
    print(val)
    exit()


# minus -> plus 

## search next p
next_p = 0
for i in range(k,len(al_abs)):
    v,sig = al_abs[i]
    if sig == 1:
        next_p = v
        break

## search next m
next_m = 0
for i in range(k,len(al_abs)):
    v,sig = al_abs[i]
    if sig == -1:
        next_m = v
        break

if next_p == 0 and next_m == 0:
    print(0)
    exit()

# last_m -> next_p
if next_p*last_p >= next_m*last_m or last_p == 0:
# if next_p > 0 and next_m == 0:
    ans = 1
    skip_flag = False
    for i in range(k):
        v,sig = al_abs[i]
        if not skip_flag and v == last_m and sig == -1:
            ans *= next_p
            skip_flag = True
        else:
            ans *= v
        # print(ans)
        ans %= MOD
    print(ans)
    exit()


# last_p -> next_m
# if next_p == 0 and next_m > 0:
elif next_p*last_p <= next_m*last_m:
    ans = 1
    skip_flag = False
    for i in range(k):
        v,sig = al_abs[i]
        if not skip_flag and v == last_p and sig == 1:
            ans *= next_m
            skip_flag = True
        else:
            ans *= v
        ans %= MOD
    print(ans)
    exit()

Submission status: Accepted

Solution code:
MOD = 10 ** 9 + 7
 
N, K = map(int, input().split())
l = list(map(int, input().split()))
pos = []
neg = []
z = 0
 
for v in l:
    if v > 0:
        pos.append(v)
    elif v < 0:
        neg.append(v)
    else:
        z += 1
pos.sort()
neg.sort()
 
if N - z < K:
    print(0)
elif N - z == K:
    if len(neg) % 2 and z:
        print(0)
    else:
        out = 1
        for v in neg + pos:
            out *= v
            out %= 10 ** 9 + 7
        print(out)
elif len(pos) == 0:
    if K % 2:
        if z:
            print(0)
        else:
            neg.reverse()
            out = 1
            for i in range(K):
                out *= neg[i]
                out %= 10 ** 9 + 7
            print(out)
    else:
        out = 1
        for i in range(K):
            out *= neg[i]
            out %= 10 ** 9 + 7
        print(out)
else:
    out = 1
    neg.reverse()
    if K % 2:
        out = pos.pop()
        K -= 1
    while K:
        if len(pos) >= 2:
            nP = pos[-1] * pos[-2]
        else:
            nP = 0
 
        if len(neg) >= 2:
            nN = neg[-1] * neg[-2]
        else:
            nN = 0
 
        if nP > nN:
            pos.pop()
            pos.pop()
            out *= nP
        else:
            neg.pop()
            neg.pop()
            out *= nN
        out %= MOD
        K -= 2
    print(out)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
al = list(map(int, input().split()))
al_abs = []
al_p = []
al_m = []
zero_cnt = 0
MOD = 10**9+7

if n == 1 and k == 1:
    print(al[0]%MOD)
    exit()

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

for a in al:
    if a == 0:
        zero_cnt+=1
    else:
        if a > 0: 
            al_abs.append((abs(a),1))
            al_p.append(a)
        elif a < 0: 
            al_abs.append((abs(a),-1))

al_abs.sort(reverse=True)
if len(al_abs) < k:
    print(0)
    exit()

if len(al_abs) == k:
    ans = 1
    m_cnt = 0
    for a,s in al_abs:
        if s == -1: m_cnt += 1
        ans *= a
        ans %= MOD
    if m_cnt%2 == 0:
        print(ans)
    else:
        print(0)
    exit()
    

if not al_p:
    if k%2 == 1 and zero_cnt > 0:
        print(0)
    else:
        if k%2 == 1:
            al_abs.sort()
        ans = 1
        for a,s in al_abs[:k]:
            ans *= (a*(-1))
            ans %= MOD
        print(ans)
    exit()



val = 1
m_cnt = 0
last_m = 0
last_p = 0
for i in range(k):
    v,sig = al_abs[i]
    val *= v
    val %= MOD
    if sig == -1:
        m_cnt += 1
        last_m = v
    else:
        last_p = v

if m_cnt %2 == 0:
    print(val)
    exit()


# minus -> plus 

## search next p
next_p = 0
for i in range(k,len(al_abs)):
    v,sig = al_abs[i]
    if sig == 1:
        next_p = v
        break

## search next m
next_m = 0
for i in range(k,len(al_abs)):
    v,sig = al_abs[i]
    if sig == -1:
        next_m = v
        break

# print(next_m, next_p)

if next_p == 0 and next_m == 0:
    print(0)
    exit()

# last_m -> next_p
if next_p*last_p >= next_m*last_m or last_p == 0:
# if next_p > 0 and next_m == 0:
    ans = 1
    skip_flag = False
    for i in range(k):
        v,sig = al_abs[i]
        if not skip_flag and v == last_m and sig == -1:
            ans *= next_p
            skip_flag = True
        else:
            ans *= v
        # print(ans)
        ans %= MOD
    print(ans)
    exit()


# last_p -> next_m
# if next_p == 0 and next_m > 0:
elif next_p*last_p <= next_m*last_m:
    ans = 1
    skip_flag = False
    for i in range(k):
        v,sig = al_abs[i]
        if not skip_flag and v == last_p and sig == 1:
            ans *= next_m
            skip_flag = True
        else:
            ans *= v
        ans %= MOD
    print(ans)
    exit()

Submission status: Accepted

Solution code:
import sys

mod = 10 ** 9 + 7
N, K = map(int,input().split())
A = list(map(int,input().split()))
if all([a < 0 for a in A]):
    if K % 2 == 0:
        A.sort()
        ans = 1
        for i in range(K):
            ans *= A[i]
            ans %= mod
        print(ans)
        sys.exit()
    else:
        A.sort(reverse = True)
        ans = 1
        for i in range(K):
            ans *= A[i]
            ans %= mod
        print(ans)
        sys.exit()

A.sort()
l = 0
r = N - 1
ans = 1

if K % 2 == 1:
    ans *= A[r]
    ans %= mod
    r -= 1

for _ in range(K // 2):
    if A[l] * A[l+1] >= A[r] * A[r-1]:
        ans *= A[l] * A[l+1]
        ans %= mod
        l += 2
    else:
        ans *= A[r] * A[r-1]
        ans %= mod
        r -= 2

print(ans)

Submission status: Accepted

Solution code:
MOD = 10 ** 9 + 7

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

alst.sort()

if n == k:
    ans = 1
    for num in alst:
        ans *= num
        ans %= MOD
    print(ans)
    exit()

if k == 1:
    print(alst[-1] % MOD)
    exit()

if alst[0] >= 0:
    ans = 1
    alst.sort(reverse = True)
    for i in range(k):
        ans *= alst[i]
        ans %= MOD
    print(ans)
    exit()

if alst[-1] <= 0:
    ans = 1
    if k % 2 == 1:
        alst = alst[::-1]
    for i in range(k):
        ans *= alst[i]
        ans %= MOD
    print(ans)
    exit()

blst = []
for num in alst:
    try:
        blst.append([abs(num), abs(num) // num])
    except ZeroDivisionError:
        blst.append([abs(num), 0])
blst.sort(reverse = True,key = lambda x:x[0])
if blst[k - 1] == 0:
    print(0)
    exit()
    
minus = 0
last_minus = 0
last_plus = 0
ans_lst = []
for i in range(k):
    if blst[i][1] == -1:
        minus += 1
        last_minus = blst[i][0]
    elif blst[i][1] == 1:
        last_plus = blst[i][0]
    else:
        print(0)
        exit()
    ans_lst.append(blst[i][0])

next_minus = 0
next_plus = 0
flg_minus = False
flg_plus = False

for i in range(k, n):
    if blst[i][1] == -1 and (not flg_minus):
        next_minus = blst[i][0]
        flg_minus = True
    if blst[i][1] == 1 and (not flg_plus):
        next_plus = blst[i][0]
        flg_plus = True
    if (flg_plus and flg_minus) or blst[i][1] == 0:
        break

if minus % 2 == 0:
    ans = 1
    for num in ans_lst:
        ans *= num
        ans %= MOD
    print(ans)

else:
    minus_s = last_minus * next_minus
    plus_s = last_plus * next_plus
    ans = 1
    if minus == k:
        ans_lst.remove(last_minus)
        ans_lst.append(next_plus)
    elif minus_s == plus_s == 0:
        if next_minus == 0:
            ans_lst.remove(last_minus)
            ans_lst.append(next_plus)
        else:
            print(0)
            exit()
        
    elif minus_s > plus_s:
        ans_lst.remove(last_plus)
        ans_lst.append(next_minus)
    else:
        ans_lst.remove(last_minus)
        ans_lst.append(next_plus)
    for num in ans_lst:
        ans *= num
        ans %= MOD
    print(ans)

Submission status: Accepted

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

s = sorted(a,reverse=True)
mod = 10**9 + 7
ans = 1
#全部の要素が負の数であり奇数個の場合は大きい順に取ったものが答え
if k % 2 == 1 and s[0] < 0:
        for i in range(k):
            ans = ans * s[i] % mod
        print(ans)
        exit()#終了

l = 0
r = n - 1
#次の処理のための計算　（kが奇数だった場合)
#この処理の必要性
#奇数個だった場合三個のうち二つで正の数の最大値を作れば良い
if k % 2 == 1:
  ans = ans * s[l]
  l += 1


for _ in range(k // 2):
  ml = s[l] * s[l + 1]
  mr = s[r] * s[r - 1]
  if ml > mr:
    ans = ans * ml % mod
    l += 2
  else:
    ans = ans * mr % mod
    r -= 2

print(ans)

Submission status: Accepted

Solution code:
mod=10**9+7
num,k=map(int,input().rstrip().split())
mai=list(map(int, input().rstrip().split()))
main=sorted(mai,key=abs,reverse=True)
result=1
def findplus_plus(x):
    for i in range(x,len(main)):
        if main[i]>=0:
            return main[i]
    return ''
def findplus_minus(x):
    for i in range(x,len(main)):
        if main[i]<0:
            return main[i]
    return ''
def findminus_plus(x):
    for i in range(x-1,-1,-1):
        if main[i]>=0:
            return main[i]
    return ''
def findminus_minus(x):
    for i in range(x-1,-1,-1):
        if main[i]<0:
            return main[i]
    return ''

if num==k:
    for i in main:
        result*=i
        result%=mod
elif sorted(main)[len(sorted(main))-1]<0:
    if (k%2)==0:
        for i in range(k):
            result*=main[i]
            result%=mod
    else:
        for i in range(len(main)-1,len(main)-1-k,-1):
            result*=main[i]
            result%=mod

else:
    count=0
    for i in range(k):
        if main[i]<0:
            count+=1
        result*=main[i]
        result%=mod
    if (count%2)==1:
        minplus=findminus_plus(k)
        minminus=findminus_minus(k)
        maxplus=findplus_plus(k)
        maxminus=findplus_minus(k)
        if type(maxplus)==type(''):
            plusplus=-1
            minusminus=minminus*maxminus
        else:
            if type(maxminus)==type('') or type(minplus)==type(''):
                minusminus=-1
                plusplus=0
            else:
                minusminus=minminus*maxminus
                plusplus=minplus*maxplus
        if plusplus>minusminus:
            main.remove(minminus)
            result=1
            for i in range(k-1):
                result*=main[i]
                result%=mod
            result*=maxplus
        elif plusplus<=minusminus:
            main.remove(minplus)
            result=1
            for i in range(k-1):
                result*=main[i]
                result%=mod
            result*=maxminus
            
print(result%mod)

Submission status: Accepted

Solution code:
from collections import defaultdict
def prod(A,k,mod):
  ans = 1
  for i in range(k):
      ans *= A[i]
      ans %= mod
  return ans
def solve():
  N, K = map(int, input().split())
  A = list(map(int, input().split()))
  mod = 10**9+7
  ans = 1
  if K==N:
    return prod(A,N,mod)
  minus = len([a for a in A if a<0])
  if minus==N:
    if K%2==0:
      A.sort()
    else:
      A.sort(reverse=True)
    return prod(A,K,mod)
  if K==1:
    return max(A)
  A.sort(key=lambda x:-abs(x))
  if A[K]==0:
    return 0
  minus = len([a for a in A[:K] if a<0])
  flag = [1]*K+[0]*(N-K)
  d = defaultdict(lambda: -1)
  if minus%2==1:
    for i in range(K,N):
      if A[i]>=0:
        d['p2'] = i
        break
    for i in range(K,N):
      if A[i]<0:
        d['m2'] = i
        break
    for i in range(K-1,-1,-1):
      if A[i]>0:
        d['p1'] = i
        break
    for i in range(K-1,-1,-1):
      if A[i]<0:
        d['m1'] = i
        break
    if d['p2']==-1 or d['m1']==-1:
      flag[d['m2']],flag[d['p1']] = 1,0
    elif d['m2']==-1 or d['p1']==-1:
      flag[d['p2']],flag[d['m1']] = 1,0
    elif A[d['p2']]*A[d['p1']]>A[d['m1']]*A[d['m2']]:
        flag[d['p2']],flag[d['m1']] = 1,0
    else:
      flag[d['m2']],flag[d['p1']] = 1,0
    ans = 1
    for i in range(N):
      if flag[i]==1:
        ans *= A[i]
        ans %= mod
    return ans
  return prod(A,K,mod)
print(solve())

Submission status: Accepted

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

s = sorted(a,reverse=True)
mod = 10**9 + 7
ans = 1

if k % 2 == 1 and s[0] < 0:
        for i in range(k):
            ans = ans * s[i] % mod
        print(ans)
        exit()

l = 0
r = n - 1
if k % 2 == 1:
  ans = ans * s[l]
  l += 1

for _ in range(k // 2):
  ml = s[l] * s[l + 1]
  mr = s[r] * s[r - 1]
  if ml > mr:
    ans = ans * ml % mod
    l += 2
  else:
    ans = ans * mr % mod
    r -= 2

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]


def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


def ceil(a, b):
    return (a + b - 1) // b


def sum_of_arithmetic_progression(s, d, n):
    return n * (2 * s + (n - 1) * d) // 2


def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)


def lcm(a, b):
    g = gcd(a, b)
    return a / g * b


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

    MOD = 10**9 + 7

    num_zero = 0
    neg_list = []
    pos_list = []
    for a in A:
        if a == 0:
            num_zero += 1
        elif a < 0:
            neg_list.append(a)
        else:
            pos_list.append(a)

    # 0にしかできない
    if len(pos_list) + len(neg_list) < K:
        print(0)
    else:
        min_num_neg = K - len(pos_list)
        max_num_neg = min(K, len(neg_list))
        # 負にしかできない
        if min_num_neg == max_num_neg and min_num_neg % 2 == 1:
            if num_zero > 0:
                print(0)
                return

            ans = 1
            neg_list.sort()
            pos_list.sort(reverse=True)
            for i in range(K):
                use_pos = False
                if len(neg_list) == 0 or len(pos_list) == 0:
                    if len(neg_list) == 0:
                        use_pos = True
                    else:
                        use_pos = False
                elif abs(neg_list[-1]) < pos_list[-1]:
                    use_pos = False
                else:
                    use_pos = True

                if use_pos:
                    ans *= pos_list[-1]
                    pos_list.pop()
                else:
                    ans *= neg_list[-1]
                    neg_list.pop()

                ans %= MOD

            print(ans)

        else:
            # 正にできる
            ans = 1

            neg_list.sort(reverse=True)
            pos_list.sort()

            if K % 2 == 1:
                K -= 1
                ans *= pos_list[-1]
                pos_list.pop()

            # posもnegも偶数個ずつ使う
            for _ in range(0, K, 2):
                use_pos = False
                if len(neg_list) <= 1 or len(pos_list) <= 1:
                    if len(neg_list) <= 1:
                        use_pos = True
                    else:
                        use_pos = False
                elif abs(neg_list[-1] * neg_list[-2]) > (pos_list[-1] * pos_list[-2]):
                    use_pos = False
                else:
                    use_pos = True

                if use_pos:
                    ans *= pos_list[-1] * pos_list[-2]
                    pos_list.pop()
                    pos_list.pop()
                else:
                    ans *= neg_list[-1] * neg_list[-2]
                    neg_list.pop()
                    neg_list.pop()

                ans %= MOD

            print(ans)


def main():
    solve()


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from functools import reduce

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

mod = 10 ** 9 + 7
if n == k:
    print(reduce(lambda ac, v: ac * v % mod, a, 1))
    exit()

a.sort(key=lambda v: abs(v), reverse=True)
if len(list(filter(lambda v: v < 0, a))) == n and k % 2 == 1:
    print(reduce(lambda ac, v: ac * v % mod, a[n - k :], 1))
    exit()

ans = 1
mn = 0
for v in a[:k]:
    if v < 0:
        mn += 1
    ans *= abs(v)
    ans %= mod

if mn % 2 == 0:
    print(ans)
    exit()

mnp, mnn = 0, 0
for v in a[k - 1 :: -1]:
    if mnp != 0 and mnn != 0:
        break
    elif mnp == 0 and v > 0:
        mnp = v
    elif mnn == 0 and v < 0:
        mnn = v
mxp, mxn = 0, 0
for v in a[k:]:
    if mxp != 0 and mxn != 0:
        break
    elif mxp == 0 and v > 0:
        mxp = v
    elif mxn == 0 and v < 0:
        mxn = v
x, y = mxp, mnn
if mnp != 0 and mxn * mnn > mxp * mnp:
    x, y = mxn, mnp
ans *= pow(abs(y), mod - 2, mod)
ans %= mod
ans *= abs(x)
ans %= mod
print(ans)

Submission status: Accepted

Solution code:
from functools import reduce

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

a.sort(key=lambda v: abs(v), reverse=True)
mod = 10 ** 9 + 7
if n == k:
    print(reduce(lambda ac, v: ac * v % mod, a, 1))
    exit()
elif len(list(filter(lambda v: v < 0, a))) == n and k % 2 == 1:
    print(reduce(lambda ac, v: ac * v % mod, a[n - k :], 1))
    exit()

ans = 1
mn = 0
for v in a[:k]:
    if v < 0:
        mn += 1
    ans *= abs(v)
    ans %= mod

if mn % 2 == 0:
    print(ans)
    exit()

mnp, mnn = 0, 0
for v in a[k - 1 :: -1]:
    if mnp != 0 and mnn != 0:
        break
    elif mnp == 0 and v > 0:
        mnp = v
    elif mnn == 0 and v < 0:
        mnn = v
mxp, mxn = 0, 0
for v in a[k:]:
    if mxp != 0 and mxn != 0:
        break
    elif mxp == 0 and v > 0:
        mxp = v
    elif mxn == 0 and v < 0:
        mxn = v
x, y = mxp, mnn
if mnp != 0 and mxn * mnn > mxp * mnp:
    x, y = mxn, mnp
ans *= pow(abs(y), mod - 2, mod)
ans %= mod
ans *= abs(x)
ans %= mod
print(ans)

Submission status: Accepted

Solution code:
def solve():
    import sys
    input = sys.stdin.readline

    mod = 10 ** 9 + 7
    n, k = map(int, input().split())
    pos, neg = [], []
    for x in map(int, input().split()):
        if x < 0:
            neg.append(x)
        else:
            pos.append(x)

    ans = 1
    neg.sort()
    pos.sort(reverse=True)
    neg_r = neg[::-1]
    lp, ln = len(pos), len(neg)

    if not pos and k & 1:
        for i in range(k):
            ans *= neg_r[i]
            ans %= mod
        print(ans)
        exit()

    x, y = 0, 0
    for i in range(k):
        if y >= ln:
            ans *= pos[x]
            ans %= mod
            x += 1
        elif x >= lp:
            ans *= neg[y]
            ans %= mod
            y += 1
        elif pos[x] >= -neg[y]:
            ans *= pos[x]
            ans %= mod
            x += 1
        else:
            ans *= neg[y]
            ans %= mod
            y += 1

    if n == k:
        print(ans)
        exit()

    if y & 1:
        ans_r = 1
        tmp1, tmp2 = -1, -1
        if y < ln and x != 0:
            tmp1 = neg[y] * neg[y - 1]
        if x < lp and y != 0:
            tmp2 = pos[x] * pos[x - 1]
        if tmp1 > tmp2:
            for i in range(x - 1):
                ans_r *= pos[i]
                ans_r %= mod
            for i in range(y + 1):
                ans_r *= neg[i]
                ans_r %= mod
        elif tmp1 <= tmp2:
            for i in range(x + 1):
                ans_r *= pos[i]
                ans_r %= mod
            for i in range(y - 1):
                ans_r *= neg[i]
                ans_r %= mod
        print(ans_r)
    else:
        print(ans % mod)


solve()

Submission status: Accepted

Solution code:
import sys
from collections import deque

import bisect


def input():
    return sys.stdin.readline().rstrip()


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

    #    print(A)
    pp = int(bisect.bisect_left(A, 0))
    A_minus = deque(A[:pp])
    A_plus = deque(A[pp:])

    AA = deque([])
    AAm = deque([])
    if N == K:
        ans = 1
        for i in A:
            ans *= i
            ans %= mod
        print(ans % mod)

    elif K % 2 == 0:
        ans = 1

        while len(A_minus) >= 2:
            a1 = A_minus.popleft()
            a2 = A_minus.popleft()
            AAm.append(a1 * a2)

        while len(A_plus) >= 2:
            a1 = A_plus.pop()
            a2 = A_plus.pop()
            AA.append(a1 * a2)

        for i in range(K // 2):
            if len(AAm) == 0:
                temp = AA.popleft()
            elif len(AA) == 0:
                temp = AAm.popleft()
            elif AAm[0] > AA[0]:
                temp = AAm.popleft()
            else:
                temp = AA.popleft()
            ans *= temp
            ans %= mod
        print(ans % mod)

    elif len(A_plus) == 0:
        ans = 1
        for i in range(K):
            ans *= A_minus.pop()
            ans %= mod
        print(ans % mod)

    else:
        ans = A_plus.pop()

        while len(A_minus) >= 2:
            a1 = A_minus.popleft()
            a2 = A_minus.popleft()
            AAm.append(a1 * a2)

        while len(A_plus) >= 2:
            a1 = A_plus.pop()
            a2 = A_plus.pop()
            AA.append(a1 * a2)

        for i in range(K // 2):
            if len(AAm) == 0:
                temp = AA.popleft()
            elif len(AA) == 0:
                temp = AAm.popleft()
            elif AAm[0] > AA[0]:
                temp = AAm.popleft()
            else:
                temp = AA.popleft()
            ans *= temp
            ans %= mod
        print(ans % mod)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N, K = mapint()
As = list(mapint())
mod = 10**9+7

pos = []
neg = []
for a in As:
    if a>=0:
        pos.append(a)
    else:
        neg.append(a)
pos.sort(reverse=True)
neg.sort()
ans = 1
lenp, lenn = len(pos), len(neg)
if (lenp+lenn)==K:
    for a in As:
        ans *= a
        ans %= mod
    print(ans)
elif lenn==0:
    for i in range(K):
        ans *= pos[i]
        ans %= mod
    print(ans)
elif lenp==0:
    if K%2==0:
        for i in range(K):
            ans *= neg[i]
            ans %= mod
        print(ans)
    else:
        neg = neg[::-1]
        for i in range(K):
            ans *= neg[i]
            ans %= mod
        print(ans)        
else:
    p, n = 0, 0
    while p+n+1<K:
        if p+2<=lenp and n+2<=lenn:
            if pos[p]*pos[p+1]>=neg[n]*neg[n+1]:
                ans *= pos[p]
                p += 1
            else:
                ans *= neg[n]*neg[n+1]
                n += 2
        elif n+2<=lenn:
            ans *= neg[n]*neg[n+1]
            n += 2
        else:
            ans *= pos[p]
            p += 1
        ans %= mod
    if p+n<K:
        ans *= pos[p]
        ans %= mod
    print(ans)