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: Wrong Answer

Solution code:
from sys import stdin,stdout
def INPUT():return list(int(i) for i in stdin.readline().split())
import math
def inp():return stdin.readline()
def out(x):return stdout.write(x)
import math as M
MOD=10**9+7
from random import randint as R
#####################################
from collections import deque as D
#first we need to know whether our answer will be negative or positive if
#negative then among the neg values take the ones which have the least abs value
n,k=INPUT()
A=INPUT()
p1=[]
n1=[]
pos=D()
neg=D()
for i in A:
    if i>0:
        p1.append(i)
    elif i<0:
        n1.append(i)
p1.sort()
n1.sort(reverse=True)
for i in range(len(p1)):
    pos.append(p1[i])
for i in range(len(n1)):
    neg.append(n1[i])
P=len(pos)
N=len(neg)
if n==k:
    ans=1
    for i in range(n):
        ans*=A[i]
        ans%=MOD
    print(ans)
elif k>len(pos)+len(neg):
    print(0)

elif P==0 and k%2==1:
    #we know for sure ans will be negative here
    if P+N!=n:
        print(0)
    else:
        ans=1
        while(k>0 and P>0 and N>0):
            if abs(neg[0])<abs(neg[0]):
                ans*=neg[0]
                ans%=MOD
                neg.popleft()
                k-=1
                N-=1
            else:
                ans*=pos[0]
                ans%=MOD
                pos.popleft()
                k-=1
                P-=1
        if k==0:
            print(ans)
        else:
            if P==0:
                while(k>0):
                    ans*=neg.popleft()
                    ans%=MOD
                    k-=1
                    N-=1
                print(ans)
            else:
                while(k>0):
                    ans*=pos.posleft()
                    ans%=MOD
                    k-=1
                    P-=1
                print(ans)


else:
    bool=False
    ans=1
    while(k>0):
        #when both are len>=2
        while(k>1 and P>=2 and N>=2):
            if pos[-1]*pos[-2]>neg[-1]*neg[-2]:
                ans=ans*pos[-1]*pos[-2]
                ans%=MOD
                pos.pop()
                pos.pop()
                k-=2
                P-=2
            else:
                ans*=neg[-1]*neg[-2]
                ans%=MOD
                neg.pop()
                neg.pop()
                k-=2
                N-=2
            #print(ans)
        if k==0:
            print(ans%MOD)
            bool=True
            break
        elif k==1:
            #answer will be positive
            if P>0:
                ans=ans*pos[-1]
                ans%=MOD
                print(ans)
                bool=True
                break
            else:
                ans*=neg[-1]
                ans%=MOD
                print(ans)
                bool=True
                break
        else:
            #till now ans is positive and k>1 in both of them
            #the combiantion possible is p->1 to inf  n->1/0 ,n->1 to inf and p->1/0
            #k>1  and one of P or N is 0 now
            if P==0:
                if k%2==0:
                    while(k>0):
                        ans*=neg[-1]
                        ans%=MOD
                        neg.pop()
                        N-=1
                        k-=1
                    print(ans)
                    bool=True
                    break
                else:
                    while(k>0):
                        ans*=neg[0]
                        ans%=MOD
                        neg.popleft()
                        N-=1
                        k-=1
                    print(ans%MOD)
                    bool=True
                    break
            elif P==1:
                if k%2==0:
                    while(k>0 and N>0):
                        ans*=neg[-1]
                        ans%=MOD
                        k-=1
                        neg.pop()
                        N-=1
                    if k>0:
                        ans*=pos[-1]
                    print(ans%MOD)
                    bool=True
                    break
                else:
                    ans*=pos[-1]
                    P-=1
                    k-=1
                    while(k>0):
                        ans*=neg[-1]
                        ans%=MOD
                        neg.pop()
                        k-=1
                        N-=1
                    print(ans)
                    bool=True
                    break

            elif N==0:
                while(k>0):
                    ans*=pos[-1]
                    ans%=MOD
                    pos.pop()
                    k-=1
                    P-=1
                print(ans)
                bool=True
                break
            elif N==1:
                while(k>0 and P>0):
                    ans*=pos[-1]
                    ans%=MOD
                    pos.pop()
                    k-=1
                    P-=1
                if k>0:
                    ans*=neg[-1]
                    ans%=MOD
                print(ans)
                bool=True
                break
            else:
                ans*=pos[-1]
                ans%=MOD
                pos.pop()
                P-=1
                k-=1

    if bool is False:
        print(ans%MOD)
#print()

Submission status: Wrong Answer

Solution code:
from sys import stdin,stdout
def INPUT():return list(int(i) for i in stdin.readline().split())
import math
def inp():return stdin.readline()
def out(x):return stdout.write(x)
import math as M
MOD=10**9+7
#####################################
from collections import deque as D
#first we need to know whether our answer will be negative or positive if
#negative then among the neg values take the ones which have the least abs value

n,k=INPUT()
A=INPUT()
p1=[]
n1=[]
pos=D()
neg=D()
for i in A:
    if i>0:
        p1.append(i)
    elif i<0:
        n1.append(i)
p1.sort()
n1.sort(reverse=True)
for i in range(len(p1)):
    pos.append(p1[i])
for i in range(len(n1)):
    neg.append(n1[i])
P=len(pos)
N=len(neg)

if k>len(pos)+len(neg):
    print(0)

elif P==0 and k%2==1:
    #we know for sure ans will be negative here
    if P+N!=n:
        print(0)
    else:
        ans=1
        while(k>0 and P>0 and N>0):
            if abs(neg[0])<abs(neg[0]):
                ans*=neg[0]
                ans%=MOD
                neg.popleft()
                k-=1
                N-=1
            else:
                ans*=pos[0]
                ans%=MOD
                pos.popleft()
                k-=1
                P-=1
        if k==0:
            print(ans)
        else:
            if P==0:
                while(k>0):
                    ans*=neg.popleft()
                    ans%=MOD
                    k-=1
                    N-=1
                print(ans)
            else:
                while(k>0):
                    ans*=pos.posleft()
                    ans%=MOD
                    k-=1
                    P-=1
                print(ans)


else:
    bool=False
    ans=1
    while(k>0):
        #when both are len>=2
        while(k>1 and P>=2 and N>=2):
            if pos[-1]*pos[-2]>neg[-1]*neg[-2]:
                ans=ans*pos[-1]*pos[-2]
                ans%=MOD
                pos.pop()
                pos.pop()
                k-=2
                P-=2
            else:
                ans*=neg[-1]*neg[-2]
                ans%=MOD
                neg.pop()
                neg.pop()
                k-=2
                N-=2
        if k==0:
            print(ans%MOD)
            bool=True
            break
        elif k==1:
            #answer will be positive
            if P>0:
                ans=ans*pos[-1]
                ans%=MOD
                print(ans)
                bool=True
                break
            else:
                ans*=neg[-1]
                ans%=MOD
                print(ans)
                bool=True
                break
        else:
            #k>1  and one of P or N is 0 now
            if P==0:
                ans*=neg[-1]
                ans%=MOD
                neg.pop()
                N-=1
                k-=1
            else:
                ans*=pos[-1]
                ans%=MOD
                pos.pop()
                P-=1
                k-=1
    if bool is False:
        print(ans%MOD)

Submission status: Wrong Answer

Solution code:
from sys import stdin,stdout
def INPUT():return list(int(i) for i in stdin.readline().split())
import math
def inp():return stdin.readline()
def out(x):return stdout.write(x)
import math as M
MOD=10**9+7
#####################################
from collections import deque as D
#first we need to know whether our answer will be negative or positive if
#negative then among the neg values take the ones which have the least abs value

n,k=INPUT()
A=INPUT()
p1=[]
n1=[]
pos=D()
neg=D()
for i in A:
    if i>0:
        p1.append(i)
    elif i<0:
        n1.append(i)
p1.sort()
n1.sort(reverse=True)
for i in range(len(p1)):
    pos.append(p1[i])
for i in range(len(n1)):
    neg.append(n1[i])
P=len(pos)
N=len(neg)

if k>len(pos)+len(neg):
    print(0)

elif k>P and (k-P)%2==1:
    #we know for sure ans will be negative here
    if P+N!=n:
        print(0)
    else:
        ans=1
        while(k>0 and P>0 and N>0):
            if abs(neg[0])<abs(neg[0]):
                ans*=neg[0]
                ans%=MOD
                neg.popleft()
                k-=1
                N-=1
            else:
                ans*=pos[0]
                ans%=MOD
                pos.popleft()
                k-=1
                P-=1
        if k==0:
            print(ans)
        else:
            if P==0:
                while(k>0):
                    ans*=neg.popleft()
                    ans%=MOD
                    k-=1
                    N-=1
                print(ans)
            else:
                while(k>0):
                    ans*=pos.posleft()
                    ans%=MOD
                    k-=1
                    P-=1
                print(ans)


else:
    bool=False
    ans=1
    while(k>0):
        #when both are len>=2
        while(k>1 and P>=2 and N>=2):
            if pos[-1]*pos[-2]>neg[-1]*neg[-2]:
                ans=ans*pos[-1]*pos[-2]
                ans%=MOD
                pos.pop()
                pos.pop()
                k-=2
                P-=2
            else:
                ans*=neg[-1]*neg[-2]
                ans%=MOD
                neg.pop()
                neg.pop()
                k-=2
                N-=2
        if k==0:
            print(ans%MOD)
            bool=True
            break
        elif k==1:
            #answer will be positive
            if P>0:
                ans=ans*pos[-1]
                ans%=MOD
                print(ans)
                bool=True
                break
            else:
                ans*=neg[-1]
                ans%=MOD
                print(ans)
                bool=True
                break
        else:
            #k>1  and one of P or N is 0 now
            if P==0:
                ans*=neg[-1]
                ans%=MOD
                neg.pop()
                N-=1
                k-=1
            else:
                ans*=pos[-1]
                ans%=MOD
                pos.pop()
                P-=1
                k-=1
    if bool is False:
        print(ans%MOD)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7
EPS = 10 ** -10

N, K = MAP()
A = LIST()

A1 = []
A2 = []
zero = 0
for a in A:
    if a > 0:
        A1.append(a)
    elif a < 0:
        A2.append(-a)
    else:
        zero += 1

B1 = np.log(np.array([1] + A1, dtype=np.longdouble))
B2 = np.log(np.array([1] + A2, dtype=np.longdouble))
A1.sort()
A2.sort()
B1.sort()
B2.sort()
acc1 = B1.cumsum()
accrev1 = B1[::-1].cumsum()
acc2 = B2.cumsum()
accrev2 = B2[::-1].cumsum()
mx = -np.inf
mn = np.inf
idx1 = (-1, -1)
idx2 = (-1, -1)
for i in range(K+1):
    j = K - i
    if len(B1) <= i or len(B2) <= j:
        continue
    if j % 2 == 0:
        sm = accrev1[i] + accrev2[j]
        if sm > mx:
            mx = sm
            idx1 = (i, j)
    else:
        sm = acc1[i] + acc2[j]
        if sm < mn:
            mn = sm
            idx2 = (i, j)

if mx != -np.inf:
    ans = 1
    n, m = idx1
    A1.reverse()
    A2.reverse()
    for i in range(n):
        ans *= A1[i]
        ans %= MOD
    for i in range(m):
        ans *= -A2[i]
        ans %= MOD
    print(ans)
elif zero:
    print(0)
else:
    ans = 1
    n, m = idx2
    for i in range(n):
        ans *= A1[i]
        ans %= MOD
    for i in range(m):
        ans *= -A2[i]
        ans %= MOD
    print(ans)

Submission status: Wrong Answer

Solution code:
from functools import reduce
import numpy as np


def mat(list):
    return reduce(lambda a,b: a*b, list)

def print_result(num):
    print(num)
    print(num%(pow(10,9)+7))

N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
A = sorted(A, key=abs, reverse=True)
A_np = np.array(A)
num_negative = np.count_nonzero(A_np<0)
if N == num_negative:
    if K % 2 == 0:
        print_result(mat(A[:K]))
    else:
        print_result(mat(A[-K:]))
elif np.count_nonzero(A_np[:K]<0) % 2 == 0:
    print_result(mat(A[:K]))
else:
    for a in A[K:]:
        if a >= 0:
            last = a
    print_result(mat(A[:K-1])*last)

Submission status: Wrong Answer

Solution code:
from functools import reduce

def mal(list):
    return reduce(lambda a,b: a*b, list)

def print_result(num):
    print(num%(pow(10,9)+7))

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

A = sorted(A, key=abs, reverse=True)
num_negative = len(list(filter(lambda x:x<0, A)))
if N == num_negative:
    if K % 2 == 0:
        print_result(mal(A[:K]))
    else:
        print_result(mal(A[-K:]))
elif len(list(filter(lambda x:x<0, A[:K]))) % 2 == 0:
    print_result(mal(A[:K]))
else:
    for a in A[K:]:
        if a >= 0:
            last = a
    print_result(mal(A[:K-1])*last)

Submission status: Wrong Answer

Solution code:
MOD = 10**9+7


def least_product(negatives, k):
    ret = 1
    for i in negatives[-k:]:
        ret *= i
    return ret % MOD


def max_product(positives, negatives, k):
    pos_index = 0
    neg_index = 0
    ret = 1
    while k > 0:
        if neg_index == len(negatives) or neg_index + 1 == len(negatives):
            ret *= positives[pos_index]
            ret %= MOD
            k -= 1
            pos_index += 1
        elif pos_index == len(positives):
            ret *= negatives[neg_index] * negatives[neg_index + 1]
            ret %= MOD
            k -= 2
            neg_index += 2
        elif pos_index + 1 == len(positives):
            if k % 2 == 0:
                ret *= negatives[neg_index] * negatives[neg_index + 1]
                ret %= MOD
                k -= 2
                neg_index += 2
            elif k % 2 == 1:
                ret *= positives[pos_index]
                ret %= MOD
                k -= 1
                pos_index += 1
        elif pos_index + 1 < len(positives) and neg_index + 1 < len(negatives):
            if (positives[pos_index] * positives[pos_index + 1] <= negatives[neg_index] * negatives[neg_index + 1]):
                ret *= negatives[neg_index] * negatives[neg_index + 1]
                ret %= MOD
                k -= 2
                neg_index += 2
            else:
                ret *= positives[pos_index]
                ret %= MOD
                k -= 1
                pos_index += 1
        else:
            print(pos_index, len(positives), neg_index, len(negatives))
    return ret % MOD


def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    negatives = list(filter(lambda x: x < 0, A))
    positives = list(filter(lambda x: x > 0, A))
    negatives.sort()
    positives.sort()
    positives.reverse()
    if len(positives) + len(negatives) < K:
        print(0)
    elif len(positives) + len(negatives) == K:
        if len(negatives) % 2 == 1:
            if N - len(positives) - len(negatives) > 0:
                print(0)
            else:
                # print(least_product(positives, negatives, K))
                ans = 1
                for a in A:
                    ans *= a
                    ans %= MOD
                print(ans)
                # negative
        else:
            print(max_product(positives, negatives, K))
            # postive
    elif len(positives) + len(negatives) > K:
        if len(positives) > 0:
            print(max_product(positives, negatives, K))
            # postive
        else:
            print(least_product(negatives, K))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def do(pos, neg, k):
	answer = []
	x = 0
	y = 0
	k = k // 2
	for i in range(k):
		if x+1 < len(pos) and y+1 < len(neg):
			if pos[x] * pos[x+1] > neg[y] * neg[y+1]:
				answer.append(pos[x])
				answer.append(pos[x+1])
				x += 2
			else:
				answer.append(neg[y])
				answer.append(neg[y+1])
				y += 2
		elif x+1 < len(pos):
			answer += pos[x:x+(k-i)*2]
			x += (k-i) * 2
		else:
			answer += neg[y:y+(k-i)*2]
	return pos[x:], answer

n, k = map(int, input().split(' '))
l = map(int, input().split(' '))
pos = []
neg = []

for i in l:
	if i >= 0:
		pos.append(i)
	else:
		neg.append(i)

pos = sorted(pos)[::-1]
neg = sorted(neg)
answer = []

if len(pos) == 0:
	if k % 2 == 0:
		answer = neg[:k]
	else:
		answer = neg[-k:]

elif k % 2 == 1:
	last = pos.pop()
	pos, answer = do(pos, neg, k)
	if pos:
		answer.append(max(pos.pop(), last))
	else:
		answer.append(last)
else:
	pos, answer = do(pos, neg, k)

s = 1
for i in answer:
	s = (s * i) % 1000000007
print(s)

Submission status: Wrong Answer

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

if N==K: #全部
    ans=1
    for i in range(N):
        ans*=A[i]
        ans%=mod
    print(ans)
    exit()
if max(A)<0 and K%2==1: #答えがマイナス
    A.sort(reverse=True)
    ans=1
    for i in range(K):
        ans*=A[i]
        ans%=mod
    print(ans)
    exit()

plus=[]
minus=[]
for i in range(N):
    if A[i]>=0:
        plus.append(A[i])
    else:
        minus.append(A[i])

plus.sort(reverse=True) #5,3,1
minus.sort() #-5,-3,-1

Submission status: Wrong Answer

Solution code:
MOD = 10**9+7


def least_product(negatives, k):
    ret = 1
    for i in negatives[-k:]:
        ret *= i
    return ret % MOD


def max_product(positives, negatives, k):
    num_products = 0
    pos_index = 0
    neg_index = 0
    ret = 1
    while k - num_products > 0:
        if pos_index + 1 < len(positives) and neg_index + 1 < len(negatives) and positives[pos_index] * positives[pos_index + 1] <= negatives[neg_index] * negatives[neg_index + 1]:
            ret *= negatives[neg_index] * negatives[neg_index + 1]
            ret %= MOD
            num_products += 2
            neg_index += 2
        elif neg_index + 1 < len(negatives) and pos_index == len(positives):
            ret *= negatives[neg_index] * negatives[neg_index + 1]
            ret %= MOD
            num_products += 2
            neg_index += 2
        else:
            ret *= positives[pos_index]
            ret %= MOD
            num_products += 1
            pos_index += 1
    # if k - num_products == 1:
    #     ret *= positives[pos_index]
    #     ret %= MOD
    return ret % MOD


def main():
    N, K = map(int, input().split())
    A = list(map(int, input().split()))
    negatives = list(filter(lambda x: x < 0, A))
    positives = list(filter(lambda x: x > 0, A))
    negatives.sort()
    positives.sort()
    positives.reverse()
    if len(positives) + len(negatives) < K:
        print(0)
    elif len(positives) + len(negatives) == K:
        if len(negatives) % 2 == 1:
            if N - len(positives) - len(negatives) > 0:
                print(0)
            else:
                # print(least_product(positives, negatives, K))
                ans = 1
                for a in A:
                    ans *= a
                    ans %= MOD
                print(ans)
                # negative
        else:
            print(max_product(positives, negatives, K))
            # postive
    elif len(positives) + len(negatives) > K:
        if len(positives) > 0:
            print(max_product(positives, negatives, K))
            # postive
        else:
            print(least_product(negatives, K))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

N_MAX = 200000 + 5
INF = 10**9 + 7
sys.setrecursionlimit(N_MAX)
MOD = 10**9 + 7


def main():

    N, K = map(int, sys.stdin.readline().rstrip().split())
    A = [int(x) for x in sys.stdin.readline().rstrip().split()]

    P, M = [], []
    # A を非負、負で振り分ける
    for i in range(N):
        n = A[i]
        if n < 0:
            M.append(n)
        else:
            P.append(n)

    # 絶対値の大きい方から並べる
    P.sort(reverse=True)
    M.sort()
    n_p = len(P)
    n_m = len(M)
    # print(P, M)

    # 全部使う
    if K == N:
        ans = 1
        for a in A:
            ans = ans * a % MOD
        print(ans)
        return

    # 全部負の場合
    if n_p == 0:
        if K % 2 == 1:  # 奇数なら小さな方から取る
            ans = 1
            for i in range(K):
                ans = ans * M[-(i + 1)] % MOD
            print(ans)
            return
        else:
            ans = 1
            for i in range(K):
                ans = ans * M[i] % MOD
            print(ans)
            return

    i, j = 0, 0
    while K > 1:
        p, m = 0, 0
        if i + 1 < n_p:
            p = P[i] * P[i + 1]
        if j + 1 < n_m:
            m = M[j] * M[j + 1]
        if p >= m:
            i += 2
        else:
            j += 2
        K -= 2

    if K == 1:
        p, m = 0, 0
        if 0 < i < n_p:
            p = P[i - 1] * P[i]
        if j + 1 < n_m:
            m = M[j] * M[j + 1]

        if p >= m:
            i += 1
        else:
            i -= 1
            j += 2

    # print(i, j)
    ans = 1
    for u in range(i):
        ans = ans * P[u] % MOD
    for v in range(j):
        ans = ans * M[v] % MOD

    print(ans)


main()

Submission status: Wrong Answer

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

pos = []
neg = []
A = list(map(int, input().split()))
for i in range(N):
    if A[i] > 0:
        pos.append(A[i])
    else:
        neg.append(A[i])

ans = 1
if len(pos) == 0:
    neg.sort()
    for i in range(K):
        ans = (ans * neg.pop()) % mod
elif N == K:
    for i in pos:
        ans = (ans * i) % mod
    for i in neg:
        ans = (ans * i) % mod
else:
    pos.sort()
    neg.sort(reverse=True)
    if K % 2 == 1:
        ans = pos.pop()
    for i in range(K//2):
        if len(pos) > 1 and len(neg) > 1:
            if pos[-1] * pos[-2] > neg[-1] * neg[-2]:
                for _ in range(2):
                    ans = ans * pos.pop() % mod
            else:
                for _ in range(2):
                    ans = ans * neg.pop() % mod
        elif len(pos) > 1:
            for _ in range(2):
                ans = ans * pos.pop() % mod
        else:
            for _ in range(2):
                ans = ans * neg.pop() % mod

print(ans)

Submission status: Wrong Answer

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()
D = [[a[i+j-k] for j in range(k)] for i in range(k)]
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Wrong Answer

Solution code:
###==================================================
### import
#import bisect
#from collections import Counter, deque, defaultdict
#from copy import deepcopy
#from functools import reduce, lru_cache
#from heapq import heappush, heappop
#import itertools
#import math
#import string
import sys
### stdin
def input(): return sys.stdin.readline().rstrip()
def iIn(): return int(input())
def iInM(): return map(int, input().split())
def iInM1(): return map(int1, input().split())
def iInLH(): return list(map(int, input().split()))
def iInLH1(): return list(map(int1, input().split()))
def iInLV(n): return [iIn() for _ in range(n)]
def iInLV1(n): return [iIn()-1 for _ in range(n)]
def iInLD(n): return [iInLH() for _ in range(n)]
def iInLD1(n): return [iInLH1() for _ in range(n)]
def sInLH(): return list(input().split())
def sInLV(n): return [input().rstrip('\n') for _ in range(n)]
def sInLD(n): return [sInLH() for _ in range(n)]
### stdout
def OutH(lst, deli=' '): print(deli.join(map(str, lst)))
def OutV(lst): print('\n'.join(map(str, lst)))
### setting
sys.setrecursionlimit(10 ** 6)
### utils
int1 = lambda x: int(x) - 1
### constants
INF = int(1e9)
MOD = 1000000007
dx = (-1, 0, 1, 0)
dy = (0, -1, 0, 1)
###---------------------------------------------------

N, K = iInM()
A = iInLH()

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

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

ans = 1
n_minus = 0
min_plus = -1
min_minus = 1
for i in range(K):
    ans = ans * A[i] % MOD
    if A[i] > 0:
        min_plus = A[i]
    elif A[i] < 0:
        min_minus = A[i]
        n_minus += 1
    else:
        ans = 0
        print(0)
        exit()
if n_minus % 2 == 0:
    print(ans % MOD)
    exit()
else:
    ## K番目以降を探してプラスとマイナスのものを見つけにいく
    next_plus = -1
    next_minus = 1
    for i in range(K, N):
        if A[i] >= 0:
            next_plus = A[i]
            break
    for i in range(K, N):
        if A[i] <= 0:
            next_minus = A[i]
            break
    ## これから数の入れ替えを行う
    if min_plus == -1: ## 初めのK個にplusがない場合
        ans = ans * pow(min_minus, MOD-2, MOD) * next_plus % MOD
    elif min_minus == 1: ## 初めのK個にminusがない場合 ## てかこれそもそもありえない
        ans = ans * pow(min_plus, MOD-2, MOD) * next_minus % MOD
    else: ## 初めのK個にplusもminusもある場合
        ## ここまでで必ずmin_plus>0, min_minus<0, next_plus>=0, next_minus<=0
        if next_plus * min_plus >= next_minus * min_minus:
            ans = ans * pow(min_minus, MOD-2, MOD) * next_plus % MOD
        else:
            ans = ans * pow(min_plus, MOD-2, MOD) * next_minus % MOD
    #print(min_plus, min_minus, next_plus, next_minus)
    print(ans % MOD)

Submission status: Wrong Answer

Solution code:
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()))
#-------------
b = np.abs(a)
b = sorted(a,reverse = True)
b_k = b[k-1] 
a_new = [a[_] for _ in range(len(a)) if b[_] >= b_k]
a_new.sort()
D = [[a_new[i+j-k] for j in range(k)] for i in range(len(a_new))]
A = (functools.reduce(operator.mul,D[_]) for _ in range(len(D)))
l_max = max(A)
waru = 10**9 + 7
print(l_max % waru)

Submission status: Wrong Answer

Solution code:
import collections

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


#N=Kで選択肢ないとき
if(N == K):
    ans = 1
    for A in As:
        ans *= A
        ans = ans % (10 ** 9 + 7)
    print(ans % (10**9 + 7))
    exit()

#ansが負となる時
if(max(As) < 0 and K % 2 == 1):
    ans = 1
    for A in As[(N-K):]:
        ans *= A
        ans = ans % (10 ** 9 + 7)
    
    print(ans %(10**9 + 7))
    exit()

#2つを組み合わせたリスト作成
calc_list = []
As_que = collections.deque(As)

ans = 1
#Nが奇数のとき、最大の値を別途抽出
if(K % 2 == 1):
    ans *= As_que.pop()

while(len(As_que) > 1):
    calc_list.append(As_que.popleft() * As_que.popleft())
    if(len(As_que) <= 1):
        break
    calc_list.append(As_que.pop() * As_que.pop())

#    print(calc_list)

#print(calc_list)

calc_list.sort(reverse=True)
#print(calc_list)

for i in range(N // 2 - 1):
    ans *= calc_list[i]
    ans = ans % (10 ** 9 + 7)
    #print(i)

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

Submission status: Wrong Answer

Solution code:
import collections

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


#N=Kで選択肢ないとき
if(N == K):
    ans = 1
    for A in As:
        ans *= A
        ans = ans % (10 ** 9 + 7)
    print(ans % (10**9 + 7))
    exit()

#ansが負となる時
if(max(As) < 0 and K % 2 == 1):
    ans = 1
    for A in As[(N-K):]:
        ans *= A
        ans = ans % (10 ** 9 + 7)
    
    print(ans %(10**9 + 7))
    exit()

#2つを組み合わせたリスト作成
calc_list = []
As_que = collections.deque(As)

ans = 1
#Nが奇数のとき、最大の値を別途抽出
if(K % 2 == 1):
    ans *= As_que.pop()

while(len(As_que) > 1):
    calc_list.append(As_que.popleft() * As_que.popleft())
#    print(calc_list)

#print(calc_list)

calc_list.sort(reverse=True)
#print(calc_list)

for i in range((N - 1) // 2):
    ans *= calc_list[i]
    ans = ans % (10 ** 9 + 7)
    #print(i)

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

Submission status: Wrong Answer

Solution code:
import collections

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


#N=Kで選択肢ないとき
if(N == K):
    ans = 1
    for A in As:
        ans *= A
        ans = ans % (10 ** 9 + 7)
    print(ans % (10**9 + 7))
    exit()

#ansが負となる時
if(max(As) < 0 and K % 2 == 1):
    ans = 1
    for A in As[(N-K):]:
        ans *= A
        ans = ans % (10 ** 9 + 7)
    
    print(ans %(10**9 + 7))
    exit()

#2つを組み合わせたリスト作成
calc_list = []
As_que = collections.deque(As)

ans = 1
#Nが奇数のとき、最大の値を別途抽出
if(K % 2 == 1):
    ans *= As_que.pop()

while(len(As_que) > 1):
    calc_list.append(As_que.popleft() * As_que.popleft())
#    print(calc_list)

#print(calc_list)

calc_list.sort(reverse=True)
#print(calc_list)

for i in range(N // 2 - 1):
    ans *= calc_list[i]
    ans = ans % (10 ** 9 + 7)
    #print(i)

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