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 = 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):
        if li[i][1] > 0:
            Plus = li[i][0]
            P = i
            P1 = False
            break
    for i in range(n-k, n):
        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:
mod = 10**9 + 7
import bisect

def do():
    n, k = map(int, input().split())
    dat = list(map(int, input().split()))
    buf = []
    nump, numm, numz = 0, 0, 0
    for i in range(n):
        if dat[i] == 0:
            numz += 1
        elif dat[i] > 0:
            nump += 1
            buf.append([dat[i], dat[i]])
        elif dat[i] < 0:
            numm += 1
            buf.append([dat[i], -dat[i]])
    indm = []
    indp = []
    # +と-を足してもk個に満たないなら 0 をかけるしかないので
    if len(buf) < k:
        print(0)
        return

    """
    for i in range(n):
        if buf[i][0] < 0:
            indm.append(i)
        else:
            indp.append(i)
    buf.sort(key=lambda x: x[1], reverse=True)
    """

    #print(nump, numm, numz)
    #print(buf)
    #print(indm)
    #print(indp)

    res = 1
    lastp = None
    lastm = None
    flagPosi = True
    for i in range(k):
        res *= buf[i][0]
        res %= mod
        if buf[i][0] > 0:
            lastp = buf[i][0]
        elif buf[i][0] < 0:
            lastm = buf[i][0]
            flagPosi = not flagPosi

    # k個選んで正なら、無条件にオッケー
    if flagPosi:
        print(res%mod)
        return

    def do2(): # negaしか作れないなら最も小さい値
        buf.sort(key=lambda x: x[1], reverse=False)
        res2 = 1
        for i in range(k):
            res2 *= buf[i][0] % mod
            res2 %= mod
        print(res2%mod)

    def do3(anti, kawari): # negaしか作れないなら最も小さい値
        ispass = False
        buf.sort(key=lambda x: x[1], reverse=True)
        res2 = 1
        for i in range(k):
            if ispass is False and buf[i][0] == anti:
                ispass = True
                continue
            res2 *= buf[i][0] % mod
            res2 %= mod
        res2 *= kawari
        print(res2%mod)

    # 負の場合は二パターン
    # 1. 正を抜いて、次に大きい負をかける
    # 2. 負を抜いて、次に大きい正をかける
    nextp = None
    nextm = None
    for i in range(k, len(buf)):
        if buf[i][0] > 0 and nextp is None:
            nextp = buf[i][0]
        elif buf[i][0] < 0 and nextm is None:
            nextm = buf[i][0]
    #print("---",lastp, lastm, nextp,nextm)
    if (lastp is None or nextm is None) and (lastm is None or nextp is None):
        # この場合、動かせないので負しかないから
        do2()
        return
    if lastp is not None and lastm is not None and nextp is not None and nextm is not None:
        # 全部あるなら戦い
        if abs(nextm / lastp) > abs(nextp / lastm):
            # pをmにした方がいいので
            do3(lastp, nextm)
            return
        else:
            do3(lastm, nextp)
            return
    # この場合、どっちしかないので
    if (lastp is None or nextm is None) and lastm is not None and lastp is not None:
        # この場合、 m-> p
        do3(lastm, nextp)
        return
    elif lastp is not None and nextm is not None:
        do3(lastp, nextm)
        return


do()

Submission status: Wrong Answer

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

if k != 1:
    for i in range(n):
        a[i] = a[i]%modu

a.sort(reverse=True)

ans = a[0]%modu

for i in range(1,k):
    ans = (ans*(a[i]))%modu

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np

mod = int(10e8+7)

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

a_ = np.abs(a)
isN = (a!=a_).astype(int)

a = a[np.argsort(a_)[::-1]]
isN = isN[np.argsort(a_)[::-1]]
a_ = np.sort(a_)[::-1]

numN = np.sum(isN)
numP = n-numN

if k==1:
    print(np.max(a))
    sys.exit()

if np.sum(isN[:k])%2==0:
    ans = 1
    for i in range(k):
        ans *= a_[i]
        ans %= mod
    print(int(ans))
    sys.exit()

if not numP:
    ans = 1
    for i in range(1, k+1)[::-1]:
        ans *= -a_[-i]
        ans %= mod

    print(int(ans))
    sys.exit()

"""
maxN = 0
maxP = 0

for i in range(k, n):
    if isN[i]:
        maxN = i
        break

for i in range(k, n):
    if not isN[i]:
        maxP = i
        break

minN = n
minP = n

for i in range(k)[::-1]:
    if isN[i]:
        minN = i
        break

for i in range(k)[::-1]:
    if not isN[i]:
        minP = i
        break

ans_1 = 1

for i in range(k):
    if i == minP:
        if maxN:
            ans_1 *= a_[maxN]
            ans_1 %= mod
        continue

    ans_1 *= a_[i]
    ans_1 %= mod

ans_2 = 1

for i in range(k):
    if i == minN:
        if maxP:
            ans_2 *= a_[maxP]
            ans_2 %= mod
        continue

    ans_2 *= a_[i]
    ans_2 %= mod

print(int(max(ans_1, ans_2)))
"""

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
N, K = map(int, input().split())
As = list(map(int, input().split()))
MOD = 10 ** 9 + 7

def multiReduce(array):
    ret = 1
    for a, s in array:
        if s == 0:
            ret = ret * a % MOD
        else:
            ret = ret * (-a) % MOD
    return ret

arr = []
for a in As:
    if a >= 0:
        arr.append((a, 0))
    else:
        arr.append((-a, 1))

arr.sort(reverse=True)

if arr[K-1][0] == 0:
    print(0)
    exit()

lastPlus = None
lastPlusIdx = None
lastMinus = None
lastMinusIdx = None
numMinus = 0
for i in range(K):
    a = arr[i]
    if a[1] == 0:
        lastPlus = a[0]
        lastPlusIdx = i
    else:
        lastMinus = a[0]
        lastMinusIdx = i
        numMinus += 1

if numMinus % 2 == 0:
    print(multiReduce(arr[:K]))
    exit()

nextPlus = None
nextMinus = None
for i in range(K, N):
    a = arr[i]
    if a[1] == 0 and nextPlus is None:
        nextPlus = a[0]
    elif a[1] == 1 and nextMinus is None:
        nextMinus = a[0]

BD = None
if lastMinus and nextPlus:
    BD = lastMinus * nextPlus
AC = None
if lastPlus and nextMinus:
    AC = lastPlus * nextMinus

if BD and (AC is None or BD >= AC):
    arr[lastMinusIdx] = (nextPlus, 0)
    print(multiReduce(arr[:K]))
    exit()
elif AC and (BD is None or BD < AC):
    arr[lastPlusIdx] = (nextMinus, 1)
    print(multiReduce(arr[:K]))
    exit()

print(multiReduce(arr[N-K:]))

Submission status: Wrong Answer

Solution code:
from collections import Counter, deque

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

MOD = 10 ** 9 + 7

c = Counter()
for a in A:
    if a == 0:
        c['0'] += 1
    elif a < 0:
        c['-'] += 1
    else:
        c['+'] += 1

if c['-'] + c['+'] < K:
    print(0)
elif (c['-'] == N and K % 2 == 1) or (N == K and c['-'] % 2 == 1):
    def f(x):
        if x == 0:
            return 10 ** 9
        else:
            return abs(x)


    A = sorted(A, key=f)
    ans = 1
    for i in range(K):
        ans *= A[i]
        ans %= MOD

    print(ans)
else:
    A = sorted(A, key=lambda x: abs(x), reverse=True)
    plus = deque()
    minus = deque()

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

    if len(minus) % 2 == 1:
        p = None
        m = None
        for i in range(K, N):
            if A[i] >= 0 and p is None:
                p = A[i]
            if A[i] < 0 and m is None:
                m = A[i]
            if p is not None and m is not None:
                break
        if m is None and p is None:
            pass
        elif len(plus) == 0:
            pass
        elif m is None and p is not None:
            minus.pop()
            plus.append(p)
        elif m is not None and p is None:
            plus.pop()
            minus.append(m)
        elif minus[-1] * m > plus[-1] * p:
            plus.pop()
            minus.append(m)
        else:
            minus.pop()
            plus.append(p)

    ans = 1
    while plus:
        ans *= plus.popleft()
        ans %= MOD
    while minus:
        ans *= minus.popleft()
        ans %= MOD

    print(ans)

Submission status: Wrong Answer

Solution code:
from bisect import *
n, k = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = a[:] 
mod = 10 ** 9 + 7
ans = 1
for i in range(n // 2):
    if a[i] < 0:
        if i % 2 == 0:
            index = bisect_left(b, -a[i])
            if index > len(b) - k:
                b.insert(index, -a[i])
        if i % 2 == 1:
            index_ = bisect_left(b, -a[i])
            if index_ > len(b) - k:
                b.insert(index_, -a[i])
            else:
                b.pop(index)
    else:
        break
    """
    if k >= 2:
        if a[i * 2 + 1] < 0:
            index = bisect_left(b, -a[i * 2 + 1])
            print(index)
            if index > len(b) - k:
                insort_left(b, -a[i * 2])
                insort_left(b, -a[i * 2 + 1])
                k -= 2
        if a[i * 2 + 1] >= 0:
            break
    print(b)
    """

b = b[::-1]
cnt_ = 0
for i in range(n):
    if b[i] != 0:
        cnt_ += 1
    if cnt_ == k:
        break

if b[i] >= 0:
    cnt = 0
    for i in range(n):
        if b[i] != 0:
            ans *= b[i]
            ans %= mod
            cnt += 1
        if cnt == k:
            break  
    print(ans)
else:
    cnt = 0
    a = a[::-1]
    for i in range(n):
        if a[i] != 0:
            ans *= a[i]
            ans %= mod
            cnt += 1
        if cnt == k:
            break  
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappop, heappush
from collections import deque

def solve():
    input = sys.stdin.readline
    N, K = map(int, input().split())
    A = [int(a) for a in input().split()]
    mod = 7 + 10 ** 9
    q = []
    for a in A:
        if a < 0: heappush(q, (a, -1))
        else: heappush(q, (-a, 1))

    qu = deque()
    minus = -1
    plus = 1
    plusFound = False
    mc = 0
    ans = 1
    for i in range(K):
        a, pm = heappop(q)
        if pm == 1:
            plusFound = True
            ans *= plus
            ans %= mod
            plus = -a
        else:
            if mc == 1:
                ans *= (minus * a) % mod
                ans %= mod
            else:
                minus = a
            mc ^= 1
        qu.append((a, pm))
    if mc == 1:
        stock = 1
        for i in range(K, N):
            a, pm = heappop(q)
            if pm == 1:
                if stock == 1:
                    ans *= (-a * plus) % mod
                    ans %= mod
                else:
                    if a > stock:
                        ans *= (minus * stock) % mod
                    else:
                        if plus * -1 <= minus: ans *= (-a * plus) % mod
                        else: ans *= (minus * stock) % mod
                    ans %= mod
                print(ans)
                break
            elif plusFound and stock == 1:
                stock = a
            qu.append((a, pm))
        else: #ここまで来るのは0以上の数が一つもない場合かK以降plusが現れない
            if plusFound:
                ans *= (minus * stock) % mod
                print(ans % mod)
                return 0

            ans = 1
            for i in range(K):
                a, pm = qu.pop()
                ans *= a
                ans %= mod
            print(ans)
    else: 
        print((ans * plus) % mod)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
 
############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input().strip()
    return(list(s[:len(s)]))
def invr():
    return(map(int,input().split()))

n, k = invr()
a = inlt()
p1 = 1
p2 = 1

mod = 10**9 + 7

a.sort(reverse = True)

for i in range(0, k):
    p1 *= a[i]

a.reverse()

for j in range(0, k):
    p2 *= a[j]

print(max(p1, p2) % mod)

Submission status: Wrong Answer

Solution code:
import sys, bisect


if(__name__ == "__main__"):

    N, K = map( int, input().strip().split() )
    divisor = 10**9+7

    list_a = list( map(int, input().strip().split()) )

    """
    left, right側の2項の積で大きい方を選択
    選べるのが残り1項ならright側を選択
    """
    multiplies = 1

    if(N==K or N==1):
        for i in range(N):
            multiplies = multiplies * list_a[i] % divisor
        print(multiplies)
    else:
        list_a.sort()
        N_negative_numbers = bisect.bisect_left(list_a, 0)
        N_select_negatives = K + N_negative_numbers -N
        flag_overzero = True
        if(N_select_negatives > 0 and N_select_negatives % 2 != 0):
            flag_overzero = False
        if(flag_overzero == True):
            left = 0
            right = N-1

            multiply_right = list_a[right] * list_a[right-1]
            flag_left = True
            while(K>0):
                if(K>1):
                    K -= 2
                    if(flag_left==True):
                        multiply_left = list_a[left] * list_a[left+1]
                    else:
                        multiply_right = list_a[right] * list_a[right-1]

                    if(multiply_left > multiply_right):

                        multiply_left %= divisor
                        multiplies = multiplies * multiply_left % divisor
                        left += 2
                        flag_left=True
                        print(multiply_left, multiplies)

                    else:
                        multiply_right %= divisor
                        multiplies = multiplies * multiply_right % divisor
                        right -= 2
                        flag_left=False
                        print(multiply_right, multiplies)

                else:
                    multiplies = multiplies * list_a[right] % divisor
                    K =0
                    print(multiplies)
        else:
            list_a = [ abs(list_a[i]) for i in range(N)]
            list_a.sort()
            for i in range(K-1):
                multiplies = multiplies * list_a[i] % divisor
            multiplies = (-1) * multiplies * list_a[K-1] % divisor

            print(multiplies)

Submission status: Wrong Answer

Solution code:
#coding: UTF-8
import itertools
from scipy.special import comb

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

out = 0
for v in itertools.combinations(inList, 2):
    tmp = 1
    for i in range(len(v)):
        tmp = tmp*v[i]
    if tmp > out: out = tmp
print(tmp)

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
                elif s1 > s2:
                    for a in ans1:
                        ans *= a
                else:
                    s1_3 = sum(abs(a) == 3 for a in ans1)
                    s2_3 = sum(abs(a) == 3 for a in ans2)
                    if s1_3 < s2_3:
                        for a in ans2:
                            ans *= a
                    elif s1_3 > s2_3:
                        for a in ans1:
                            ans *= a
                    else:
                        for a in ans1:
                            ans *= a
    print(int(ans) % MOD)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import random

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

k = 1
for i in range(K):
    i = random.choice(A)
    k *= i

print(abs(k % (10**9+7)))

Submission status: Wrong Answer

Solution code:
mod=1000000007
def maxp(A, n, k): 
  
    # sorting given input array 
    A.sort() 
  
    # variable to store final product of  
    # all element of sub-sequence of size k 
    product = 1
  
    # CASE I 
    # If max element is 0 and 
    # k is odd then max product will be 0 
    if (A[n - 1] == 0 and (k & 1)): 
        return 0
  
    # CASE II 
    # If all elements are negative and 
    # k is odd then max product will be 
    # product of rightmost-subarray of size k 
    if (A[n - 1] <= 0 and (k & 1)) : 
        for i in range(n - 1, n - k - 1, -1): 
            product=(product%mod* A[i]%mod)%mod 
        return product%mod 
  
    # else 
    # i is current left pointer index 
    i = 0
  
    # j is current right pointer index 
    j = n - 1
  
    # CASE III 
    # if k is odd and rightmost element in 
    # sorted array is positive then it 
    # must come in subsequence 
    # Multiplying A[j] with product and 
    # correspondingly changing j 
    if (k & 1): 
        product=(product%mod* A[j]%mod)%mod 
        j-=1
        k-=1
  
    # CASE IV 
    # Now k is even. So, Now we deal with pairs 
    # Each time a pair is multiplied to product 
    # ie.. two elements are added to subsequence  
    # each time. Effectively k becomes half 
    # Hence, k >>= 1 means k /= 2 
    k >>= 1
  
    # Now finding k corresponding pairs to get 
    # maximum possible value of product 
    for itr in range( k) : 
  
        # product from left pointers 
        left_product = (A[i]%mod * A[i + 1]%mod)%mod 
  
        # product from right pointers 
        right_product = (A[j]%mod* A[j - 1]%mod)%mod 
  
        # Taking the max product from two  
        # choices. Correspondingly changing 
        # the pointer's position 
        if (left_product > right_product) : 
            product =(product%mod* left_product%mod)%mod
            i += 2
          
        else : 
            product =(product%mod*right_product%mod)%mod
            j -= 2
  
    # Finally return product 
    return product%mod
  
# Driver Code 
if __name__ == "__main__": 
      
    n, k = [int(x) for x in input().split()]
    a = list(map(int,input().strip().split()))[:n]
    print(maxp(a,n,k)%mod)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
def Ii():return int(sys.stdin.readline())
def Mi():return map(int,sys.stdin.buffer.readline().split())
def Li():return list(map(int,sys.stdin.buffer.readline().split()))

n,k = Mi()
mod = 10**9+7
a = np.array(sorted(Li(),reverse=True))
isflag = 0
#b = sorted(np.abs(a),reverse=True)
ans = 1
if n == k:
  for i in range(k): ans = ans*a[i]%mod
  print(ans)
  exit(0)
plus = sum(a>0)
if plus == 0:
  if k%2 == 1:
    for i in range(k): ans = ans*a[i]%mod
  else:
    for i in range(k): ans = ans*a[n-i-1]%mod
  print(ans)
  exit(0)
i = 0
for i in range(k-1):
  idma = np.argmax(np.abs(a))
  ans = ans*np.max(np.abs(a))%mod
  #a.pop(idma)
  isflag = (isflag+(a[idma]>0))
  if plus == isflag+1:
    break
  a = np.delete(a,idma)
  
if k%2 == isflag%2:
  for j in range(k-i-1):
    ans = ans*abs(a[-j-1])%mod
else :
  ans = ans*a[0]%mod
  for j in range(k-i-2):
    ans = ans*abs(a[-j-1])%mod
    
print(ans)

Submission status: Wrong Answer

Solution code:
from queue import PriorityQueue
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
# sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


mod = 10**9+7


def prod(l):
    ret = 1
    for e in l:
        e %= mod
        ret = (ret*e) % mod

    return ret


def main():
    n, k = geta(int)
    a = list(geta(int))

    p, n, z = [], [], 0
    for ai in a:
        if ai > 0:
            p.append(ai)
        elif ai < 0:
            n.append(-ai)
        else:
            z += 1

    ans = 1
    p.sort()
    n.sort()
    if k & 1 == 1:
        if len(p) == 0:
            if z > 0:
                print(0)
                exit()
            else:
                print(-prod(n[0:k]) % mod)
                exit()
        else:
            k -= 1
            ans = p.pop() % mod

    if len(p) + len(n) < k:
        print(0)
        exit()

    q = []

    n = n[::-1]
    for i in range(len(n)//2):
        q.append(n[2*i]*n[2*i+1])

    p = p[::-1]
    for i in range(len(p)//2):
        q.append(p[2*i]*p[2*i+1])

    q.sort(reverse=True)

    ans = ans * (prod(q[:k//2])) % mod

    print(ans % mod)


if __name__ == "__main__":
    main()

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

if K % 2 == 1:
  aaaaa
  
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)