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:
n, k = (int(x) for x in input().split())
A = list(int(x) for x in input().split())
MOD = 10**9 + 7
P = []
M = []
Z = []
for a in A:
    if a < 0:
        M.append(a)
    elif a > 0:
        P.append(a)
    else:
        Z.append(a)
P.sort()
M.sort(reverse=True)
lp = len(P)
lm = len(M)
lz = len(Z)

# どうしてもマイナスになるとき
if (lp + lm <= k and lm % 2 == 1) or (lp == 0 and k % 2 == 1):
    if lz > 0:
        print(0)
        exit()
    else:
        tmp = 1
        M.sort(reverse=True)
        for m in M[:k]:
            tmp *= m
        print(tmp % MOD)
        exit()

# プラスにできそうなとき
ans = 1
pindex = lp-1
mindex = lm-1
for _ in range(k // 2):
    if pindex > 0 and mindex > 0:
        p = P[pindex] * P[pindex - 1]
        m = M[mindex] * M[mindex - 1]
        if p > m:
            ans *= p
            ans %= MOD
            pindex -= 2
        else:
            ans *= m
            ans %= MOD
            mindex -= 2
    else:
        if pindex > 0:
            ans *= P[pindex] * P[pindex - 1]
            ans %= MOD
            pindex -= 2
        elif mindex > 0:
            ans *= M[mindex] * M[mindex - 1]
            ans %= MOD
            mindex -= 2

if k % 2 == 0:
    print(ans)
    exit()
else:
    if pindex >= 0:
        ans *= P[pindex]
        ans %= MOD
        print(ans)
    else:
        print(0)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
li_a = list(map(int, input().split()))
mod = 10**9+7
li = []
lll = 0
for i in li_a:
    if i < 0:
        li.append((abs(i), -1))
        lll += 1
    else:
        li.append((i, 1))
li.sort()
if lll == n:
    ans = 1
    for i in range(k):
        ans *= -li[i][0]
        ans %= mod
    print(ans)
    exit()
ans = 1
guki = 1
for i in range(n-1, n-k-1, -1):
    ans *= li[i][0]
    ans %= mod
    guki *= li[i][1]
if guki > 0:
    print(ans)
else:
    P, M, p, m = 10**6, 1000000, 1000000, 1000000
    P1, M1, p1, m1 = True, True, True, True
    for i in range(n-k, n-1):
        if li[i][1] > 0:
            Plus = li[i][0]
            P = i
            P1 = False
            break
    for i in range(n-k, n-1):
        if li[i][1] < 0:
            Mini = li[i][0]
            M = i
            M1 = False
            break
    if n-k-1 >= 0:
        for i in range(n-k-1, -1, -1):
            if li[i][1] > 0:
                plus = li[i][0]
                p = i
                p1 = False
                break
        for i in range(n-k-1, -1, -1):
            if li[i][1] < 0:
                mini = li[i][0]
                m = i
                m1 = False
                break
    ans1 = 1
    ans2 = 1
    if (not P1) and (not m1):
        for i in range(n-1, n-k-1, -1):
            if i == P:
                continue
            ans1 *= li[i][0]
            ans1 %= mod
        ans1 *= li[m][0]
        ans1 %= mod
    if (not p1) and (not M1):
        for i in range(n-1, n-k-1, -1):
            if i == M:
                continue
            ans2 *= li[i][0]
            ans2 %= mod
        ans2 *= li[p][0]
        ans2 %= mod
    if not p1 and not P1 and not M1 and not m1:
        if mini/Plus < plus/Mini:
            print(ans1)
        else:
            print(ans2)
    elif not p1 and not M1:
        print(ans2)
    elif not m1 and not P1:
        print(ans1)
    else:
        ans = 1
        for i in range(k):
            ans *= -li[i][0]
            ans %= mod
        print(ans)

Submission status: Wrong Answer

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

a.sort(reverse=True, key=lambda x:abs(x))
cnt = 0
im = 0
ip = 0
cp = 0
mod = 10 ** 9 + 7

for i, ai in enumerate(a):
    if i < k:
        if ai < 0:
            im = i
            cnt += 1
        if ai > 0:
            ip = i
    if ai > 0:
        cp += 1

ans = 1
f = 0

# print(a)
if cnt % 2:
    if cp == 0:
        a.sort(reverse=True)
        for i, ai in enumerate(a):
            if i == k:
                break
            ans *= ai
            ans %= mod
        print(ans)
    else:
        ans = 1
        cnt = 0
        f = 0
        for i, ai in enumerate(a):
            if cnt == k:
                f = 2
                break
            if i == im:
                f = 1
                continue
            if f == 1 and ai <= 0:
                continue
            ans *= abs(ai)
            ans %= mod
            # print(i, ai)
            cnt += 1
        if f == 2:
            print(ans)
        else:
            ans = 1
            cnt = 0
            f = 0
            for i, ai in enumerate(a):
                if cnt == k:
                    break
                if i == ip:
                    f = 1
                    continue
                if f == 1 and ai > 0:
                    continue
                ans *= abs(ai)
                ans %= mod
                # print(i, ai)
                cnt += 1
            print(ans)

else:
    for i, ai in enumerate(a):
        if i == k:
            break
        ans *= abs(ai)
        ans %= mod
    print(ans)

Submission status: Wrong Answer

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

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

# 正に出来る場合：
# ・すべて正の数を選べる
# ・選べる数が奇数個で、負の数が偶数個と正の数が1個以上存在する
# ・選べる数が偶数個で、負の数が偶数個存在する
# 負になる場合：
# ・すべて負の数で且つ、選べる数が奇数個
# ・0が存在していれば、0のほうがマシ

# 開始時点で、絶対値が少ないほうを目指すか大きいほうを目指すか決まる
# 負の数を目指す場合、大きいほうからK個掛ければOK

# 大きいほうを目指す場合、
# 正の数の大きい順リスト [2,1]
# 負の数の絶対値大きい順リスト [-4,-3]
# の先頭から、2個のペアが大きくなるほうを貪欲に取っていく。
# 取れる数が奇数の場合は、まず正のほうの一番大きいのを取っちゃえばOK

pluslist = []
minuslist = []
zerocnt = 0
for i in range(len(A)):
  if A[i] > 0:
    pluslist.append(A[i])
  elif A[i] < 0:
    minuslist.append(A[i])
  else:
    zerocnt += 1
    
# 必ずゼロを選んでしまう場合
if N - zerocnt < K:
  print(0)
  exit(0)
  
if K % 2 == 1 and len(pluslist) == 0:
  # 負になる場合
  if zerocnt > 0:
    print(0)
    exit(0)
  # 絶対値が小さい状態を目指す
  minuslist = sorted(minuslist, reverse = True)
  ans = 1
  for i in range(K):
    ans *= minuslist[i]
    ans %= DIV
  print(ans)
  exit(0)
  
if K + zerocnt == N:
  if len(minuslist) % 2 == 1 and zerocnt > 0:
    print(0)
    exit(0)

# 正の数を目指す
pluslist = sorted(pluslist, reverse = True)
minuslist = sorted(minuslist)
from collections import deque

plusq = deque(pluslist)
minusq = deque(minuslist)



ans = 1
# この時点で、正にすることが出来る。
# Kが奇数の場合、最低でも1回正の数を使う必要がある
if K % 2 == 1 and len(plusq) > 0:
  ans *= plusq.popleft() # 一番大きいものを取っておく
  K -= 1

for i in range(K // 2):
  p = 0
  m = 0
  if len(plusq) >= 2:
    p1 = plusq.popleft()
    p2 = plusq.popleft()
    p = p1 * p2
  if len(minusq) >= 2:
    m1 = minusq.popleft()
    m2 = minusq.popleft()
    m = m1 * m2
  if p == 0 and m == 0:
    ans *= (minusq.popleft() * plusq.popleft()) % DIV
    continue
  if m == 0:
    ans *= p % DIV
    ans %= DIV
    continue
  if p == 0:
    ans *= m % DIV
    ans %= DIV
    continue
  if p > m:
    ans *= (p1 * p2) % DIV
    ans %= DIV
    minusq.appendleft(m2)
    minusq.appendleft(m1)
  else:
    ans *= (m1 * m2) % DIV
    ans %= DIV
    plusq.appendleft(p2)
    plusq.appendleft(p1)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from math import log2
from itertools import accumulate

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 = []
B1 = []
B2 = []
zero = 0
for a in A:
    if a > 0:
        A1.append(a)
        B1.append(log2(a))
    elif a < 0:
        A2.append(-a)
        B2.append(log2(-a))
    else:
        zero += 1

A1.sort()
A2.sort()
B1.sort()
B2.sort()
acc1 = [0] + list(accumulate(B1))
accrev1 = [0] + list(accumulate(B1[::-1]))
acc2 = [0] + list(accumulate(B2))
accrev2 = [0] + list(accumulate(B2[::-1]))
mx = -INF
mn = 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 - EPS > mx:
            mx = sm
            idx1 = (i, j)
    else:
        sm = acc1[i] + acc2[j]
        if sm < mn - EPS:
            mn = sm
            idx2 = (i, j)

if mx != -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 collections import deque
n,k = map(int,input().split())
a = list(map(int,input().split()))
mod = 10**9+7
p = []
m = []
ans = 1
for i in a:
    if i < 0:
        m.append(-i)
    else:
        p.append(i)
cp = len(p)
cm = len(m)
m.append(0)
m.append(0)
p.append(0)
p.append(0)
p.sort()
m.sort()
p = deque(p)
m = deque(m)
p1 = deque.pop(p)
p2 = deque.pop(p)
if cp>=k or (k-cp)%2 == 0:
    f = 0
else:
    f = 1 
while k:
    # print(k,cm,m)
    if k%2 == 1 and cp:
        ans *= p1
        p1 = p2
        p2 = deque.pop(p)
        k -= 1
        cp -= 1
    elif m[-1] * m[-2] > p1 * p2 and cm > 1 and k>1:
        m1 = deque.pop(m)
        m2 = deque.pop(m)
        ans *= m1 * m2
        cm -= 2
        k -= 2
    elif cp > 0:
        ans *= p1
        p1 = p2
        p2 = deque.pop(p)
        k -= 1
        cp -= 1
    else:
        
        ans *= -m[2]
        m1 = deque.popleft(m)
        m2 = deque.popleft(m)
        m3 = deque.popleft(m)
        deque.appendleft(m,m1)
        deque.appendleft(m,m2)
        cm -= 1
        k -= 1
    ans %= mod
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
#import bisect
#import numpy as np
# from collections import deque
from collections import deque
# map(int, sys.stdin.read().split())
import itertools
import heapq

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()
    A = deque(A)
#    print(A)
    A_minus = deque([s for s in A if s <0])
    A_plus =deque( [s for s in A if s >=0])

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

    elif K%2 ==0:
        while len(A_minus)>=2:
            a1 = A_minus.popleft()
            a2 = A_minus.popleft()
            AA.append(-a1*a2)

        while len(A_plus)>=2:
            a1 =A_plus.pop()
            a2 =A_plus.pop()
            AA.append(-a1*a2)
        ans =1
        heapq.heapify(AA)
        for i in range(K//2):
            ans *= (-1 * heapq.heappop(AA)) %mod
        print(ans%mod)

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

    else:
        ans = A_plus.pop()
        while len(A_minus)>=2:
            a1 = A_minus.popleft()
            a2 = A_minus.popleft()
            AA.append(-a1*a2)

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

        heapq.heapify(AA)
        for i in range(K//2):
            ans *= (-1 * heapq.heappop(AA)) %mod
        print(ans)









if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
list1 = list(map(int,input().split()))
list1.sort()
m1 = 1
m2=1
for i in range(k):
    m1 = m1 * list1[i]
    m2 = m2 * list1[(n-1)-i]
if m1 > m2 :
    print(m1)
else:
    print(m2)

Submission status: Wrong Answer

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

ret = 1
mod = 10 ** 9 + 7

left = k
mptr = 0
pptr = len(a) - 1
mls = []
a.sort()
for i in range(len(a)):
    if i % 2 == 0:
        continue
    else:
        if a[i] < 0 and a[i-1] < 0:
            mls.append((a[i] * a[i-1], 2))
        else:
            break

for item in a:
    if item > 0:
        mls.append((item, 1))

mls.sort()
mls.reverse()
ptr = 0

while left > 0:
    if ptr >= len(mls):
        break
    else:
        tmp = mls[ptr]
        if left > 1:
            ret = (mls[ptr][0] % mod) * ret % mod
            left -= mls[ptr][1]
            ptr += 1
        else:
            if mls[ptr][1] == 2:
                ptr += 1
            else:
                ret = (mls[ptr][0] % mod) * ret % mod
                break

if left == 0:
    print(ret % mod)
else:
    a.sort(key=lambda x: abs(x))
    ret = 1
    for i in range(k):
        ret *= a[i] % (10 ** 9 + 7)
        if ret == 0:
            break
    print(ret % (10 ** 9 + 7))

Submission status: Wrong Answer

Solution code:
def main():
    MOD = 10 ** 9 + 7

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

    A.sort(key=abs, reverse=True)

    ans = 1
    sgn = 1

    lm, lp = None, None
    for i, x in enumerate(A[:K]):
        if x < 0:
            sgn = -sgn
            lm = x
        else:
            lp = x
        ans = ans * abs(x) % MOD

    if K == N or sgn == 1 or ans == 0:
        print(ans)
        return

    fm, fp, z = None, None, False
    for i, x in enumerate(A[K:]):
        if x < 0:
            if fm is None:
                fm = x
        elif x == 0:
            z = True
        else:
            if fp is None:
                fp = x

    # 交換できる場合
    if lp is None:
        # マイナスが奇数個のみ
        if fp is not None:
            ans = ((ans * pow(lm, MOD - 2, MOD)) % MOD) * fp % MOD
            print(ans)
            return

        if z:
            print(0)
            return

        A.sort(key=abs)
        ans = 1
        sgn = 1
        for i, x in enumerate(A[:K]):
            if x < 0:
                sgn = -sgn
            ans = ans * abs(x) % MOD
        ans = ans * sgn % MOD
        print(ans)
        return

    else:
        if fp is not None and fm is not None:
            if fm * lm >= fp * lp:
                ans = ((ans * pow(lp, MOD - 2, MOD)) % MOD) * fm % MOD
                print(ans % MOD)
                return
            else:
                ans = ((ans * pow(lm, MOD - 2, MOD)) % MOD) * fp % MOD
                print(ans % MOD)
                return

        if fp is not None:
            ans = ((ans * pow(lm, MOD - 2, MOD)) % MOD) * fp % MOD
            print(ans)
            return

        if fm is not None:
            ans = ((ans * pow(lp, MOD - 2, MOD)) % MOD) * fm % MOD
            print(ans)
            return


if __name__ == '__main__':
    main()

# import sys
# input = sys.stdin.readline
# 
# sys.setrecursionlimit(10 ** 7)
# 
# (int(x)-1 for x in input().split())
# rstrip()
#
# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict, Counter, namedtuple, deque
import itertools
import functools
import bisect
import heapq
import math
import copy
# from fractions import gcd

MOD = 10 ** 9 + 7
# MOD = 998244353
# sys.setrecursionlimit(10**8)


n, k = map(int, input().split())
A = list(map(int, input().split()))
pos = []
neg = []
for i in range(n):
    if A[i] < 0:
        neg.append(A[i])
    elif A[i] > 0:
        pos.append(-A[i])

if len(pos) + len(neg) < k:
    print(0)
    exit()

pos.sort()
neg.sort()
# print(pos, neg)

if len(pos) == 0:
    if k%2 == 1:
        if n - (len(pos) + len(neg)) > 0:
            print(0)
            exit()
        ans = 1
        for i in range(1, k+1):
            ans = (ans * neg[-i]) % MOD
        print(ans)
        exit()
    else:
        ans = 1
        for i in range(k):
            ans = (ans * neg[i]) % MOD
        print(ans)
        exit()

elif len(neg) == 0:
    ans = 1
    for i in range(k):
        ans = (ans * -pos[i]) % MOD
    print(ans)
    exit()

else:
    mix = pos + neg
    mix.sort()
    val = mix[k-1]
    pos_idx = bisect.bisect(pos, val) - 1
    neg_idx = bisect.bisect(neg, val) - 1
    pos_idx2 = bisect.bisect_left(pos, val) - 1
    neg_idx2 = bisect.bisect_left(neg, val) - 1
    # print(pos_idx, neg_idx, pos_idx2, neg_idx2)
    if pos_idx + neg_idx + 2 > k:
        rem = k-2-pos_idx2-neg_idx2
        if neg_idx2%2 == 0 and neg_idx2 < neg_idx:
            neg_idx2 += 1
            rem -= 1
        while neg_idx2+1 < neg_idx and rem >= 2:
            neg_idx2 += 2
            rem -= 2
        while rem >= 1:
            pos_idx2 += 1
            rem -= 1
        pos_idx = pos_idx2
        neg_idx = neg_idx2

    # print(pos_idx, neg_idx)

    if neg_idx % 2 == 0:
        if neg_idx == len(neg)-1 and pos_idx == len(pos)-1:
            print(0)
            exit()
        elif neg_idx == len(neg)-1:
            neg_idx -= 1
            pos_idx += 1
        elif pos_idx == len(pos)-1:
            neg_idx += 1
            pos_idx -= 1
        else:
            if neg[neg_idx+1] <= pos[pos_idx+1]:
                neg_idx -= 1
                pos_idx += 1
            else:
                neg_idx += 1
                pos_idx -= 1

    # print(pos_idx, neg_idx)
    ans = 1
    for i in range(pos_idx+1):
        ans = (ans * -pos[i]) % MOD
    for i in range(neg_idx + 1):
        ans = (ans * neg[i]) % MOD
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
N, K = map(int, input().split())
A = sorted(list(map(int, input().split())), key=lambda x: abs(x))[::-1]
P = int(1e9+7)
hu_cnt = []

ans = 1
hu = None
sei = 1
flg = False
for a in A:
    flg = a > 0
    if flg:
        break
if not flg:
    for i in range(1, K+1):
        ans = (ans * A[-i]) % P
    print(ans)
    sys.exit()
if K == N:
    for a in A:
        ans = (ans * a) % P
    print(ans)
    sys.exit()

for i, a in zip(range(K), A):
    if a > 0:
        ans = (ans * sei) % P
        sei = a
    else:
        if not hu:
            hu = a
        else:
            ans = (ans * a * hu) % P
            hu = None

ptn1, ptn2 = -1, -1
if hu:
    for i in range(K, N):
        if A[i] > 0:
            ptn1 = sei * A[i]
            break
    for i in range(K, N):
        if A[i] <= 0:
            ptn2 = hu * A[i]
            break
    ans = (ans * max(ptn1, ptn2)) % P
else:
    ans = (ans * sei) % P
print(ans%P)

Submission status: Wrong Answer

Solution code:
from heapq import *
import sys
from collections import *
from itertools import *
from decimal import *
import copy
from bisect import *
import math
sys.setrecursionlimit(4100000)
def gcd(a,b):
    if(a%b==0):return(b)
    return (gcd(b,a%b))
input=lambda :sys.stdin.readline().rstrip()
N,K=map(int,input().split())

A=list(map(int,input().split()))
mod=10**9+7
Am=[-i for i in A if i<0]
Ap=[i for i in A if i>=0]

Am.sort()
Ap.sort()
Am=deque(Am)
Ap=deque(Ap)



if N-K==0 and len(Am)%2==0 or len(Ap)==0 and K%2:
    c=1
    while K and (Am or Ap) :
        if Am and Ap:
            if Am[0]<Ap[0]:
                c*=Am.popleft()
            else:
                c*=Ap.popleft()
        elif Am:
            c*=Am.popleft()
        elif Ap:
            c*=Ap.popleft()
        K-=1
        c=-c
        c%=mod
    #print("unko")

else:
    c=1
    while K and (len(Am)>=2 or Ap) :
        if K==1 and len(Ap)==0:
            c*=pow(a,mod-2,mod)
            b=Am.pop()
            c*=b
            bb=Am.pop()
            c*=bb
            c%=mod
            break

        if K>=2 and len(Am)>=2:
            if len(Am)>=2 and len(Ap)>=2:
                if Ap[-1]*Ap[-2]>Am[-1]*Am[-2]:
                    a=Ap.pop()
                    c*=a
                    aa=Ap.pop()
                    c*=aa
                else:
                    b=Am.pop()
                    c*=b
                    bb=Am.pop()
                    c*=bb
                K-=2
            elif len(Ap)==1 and len(Am)>=2:
                if Ap[-1]>Am[-1]*Am[-2]:
                    a=Ap.pop()
                    c*=a
                    K-=1
                else:
                    b=Am.pop()
                    c*=b
                    bb=Am.pop()
                    c*=bb
                    K-=2
            else:
                b=Am.pop()
                c*=b
                bb=Am.pop()
                c*=bb
                K-=2
        else:
            a=Ap.pop()
            K-=1
        c%=mod
print(c%mod)

Submission status: Wrong Answer

Solution code:
MOD = 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():
    from collections import Counter
    N, K = (int(i) for i in input().split())
    A = [int(i) for i in input().split()]
    posi = [a for a in A if a > 0]
    nega = [a for a in A if a < 0]
    posi.sort(reverse=True)
    nega.sort(reverse=True)
    A.sort(reverse=True, key=abs)
    if len(posi) + len(nega) < K:
        # 0を含まなければいけないとき
        return print(0)

    ans = modint(1)
    if K % 2 == 1 and len(posi) < K:
        # 結果が負数
        # 絶対値が小さいやつをK個取ってくる
        A.sort(key=abs)
        for a in A[:K]:
            ans *= a
    else:
        # 結果が正になるように注意しなければいけない
        # skipしてかけるものがなくなったらこわい
        # 負数がK以下の奇数個しかないとハマる
        if sum(a < 0 for a in A[:K]) % 2 == 0:
            for a in A[:K]:
                ans *= a
        else:
            ans1 = []  # 正を取り除く
            ans2 = []  # 負を取り除く
            posi = [a for a in A[:K] if a > 0]
            nega = [a for a in A[:K] if a < 0]
            p_remove = False
            for a in A[:K][::-1]:
                if a > 0 and not p_remove:
                    p_remove = True
                    continue
                ans1.append(a)
            n_remove = False
            for a in A[:K][::-1]:
                if a < 0 and not n_remove:
                    n_remove = True
                    continue
                ans2.append(a)
            mul1 = 0  # 一番大きい正
            mul2 = 0  # 　一番大きい負
            for a in A[K:]:
                if mul1 == 0 and a > 0:
                    mul1 = a
                if mul2 == 0 and a < 0:
                    mul2 = a
                if mul1 != 0 and mul2 != 0:
                    break
            ans1.append(mul2)
            ans2.append(mul1)
            s1 = sum(abs(a) for a in ans1)
            s2 = sum(abs(a) for a in ans2)

            if len(posi) == 0 or mul2 == 0:
                for a in ans2:
                    ans *= a
            elif len(nega) == 0 or mul1 == 0:
                for a in ans1:
                    ans *= a
            else:
                if s1 < s2:
                    for a in ans2:
                        ans *= a
                else:
                    for a in ans1:
                        ans *= a
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def maxProductSubarrayOfSizeK(A, n, k):
    A.sort()
    product = 1

    if (A[n - 1] == 0 and (k & 1)):
        return 0

    if (A[n - 1] <= 0 and (k & 1)):
        for i in range(n - 1, n - k + 1, -1):
            product *= A[i]
        return product

    i = 0
    j = n - 1
    if (k & 1):
        product *= A[j]
        j -= 1
        k -= 1

    k >>= 1
    for itr in range(k):
        left_product = A[i] * A[i + 1]
        right_product = A[j] * A[j - 1]
        if (left_product > right_product):
            product *= left_product
            i += 2

        else:
            product *= right_product
            j -= 2
    return product
if __name__ == "__main__":
    n,k=map(int,input().split())
    A = [int(x) for x in input().split()]
    print(maxProductSubarrayOfSizeK(A, n, k)%(10**9+7))

Submission status: Wrong Answer

Solution code:
from collections import deque
N,K=map(int,input().split())
A=list(map(int,input().split()))
A.sort(reverse=True)
d=deque(A)
import time
l=[]
if K%2==0 or (K%2==1 and A[0]>=0):
  for i in range(K//2):
    if d[0]*d[1]>d[-1]*d[-2] and len(d)>2 and d[2]>0:
      l.append(d.popleft())
      l.append(d.popleft())
    else:
      l.append(d.pop())
      l.append(d.pop())
  if K%2==1:
    if d[0]<0:time.sleep(2)
    l.append(d[0])
else:
  for i in range(K):
    l.append(d.popleft())
      
ans=1
for i in l:
  ans*=i
  ans%=10**9+7
print(ans)

Submission status: Wrong Answer

Solution code:
def checkio(numbers_array):
    return sorted(numbers_array, key=lambda x: abs(x))

P = 10**9+7
N,K = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
A = checkio(A)
a = 1
for i in range(N):
    if A[i] > 0:
        a = 0
        break
ans = 1
if a:
    for i in range(K):
        ans = ans*A[i]%P
    print(ans)
    exit()

A.reverse()
T = 1
M = -1
L = 1
for i in range(K-1):
    ans = ans*A[i]%P
    if A[i] < 0:
        T *= -1
        L = A[i]
    else:
        M = A[i]

if (T == 1 and A[K-1]>= 0) or (T == -1 and A[K-1] <= 0):
    ans = ans*A[K-1]%P
    print(ans)
    exit()
if M == -1 or T==1:
    for i in range(K-1,N):
        if A[i] >= 0:
            ans = ans*A[i]%P
            break
    print(ans)
    exit()
if T == -1:
    for i in range(K-1,N):
        if A[i] <= 0:
            ans = ans*A[i]%P
            break
    print(ans)
    exit()

Submission status: Wrong Answer

Solution code:
import numpy as np
n,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
s=1
c=0
l=0
r=-1
c1=0
while True:
    if k-c>=2:
        if a[r]*a[r-1]>=a[l]*a[l+1]:
            s*=a[r]*a[r-1]
            r-=2
            c+=2
        else:
            s*=a[l]*a[l+1]
            l+=2
            c+=2
    else:
        if a[r]<0:
            s=1
            a=np.absolute(a)
            a=list(a)
            a.sort()
            while True:
                s*=a[c1]
                c1+=1
                s%=10**9+7
                if c1==k:
                    s=-s
                    print(s%10**9+7)
                    exit()
        else:s*=a[r]
        c+=1
    s%=10**9+7
    if k==c:break
print(s)