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())
A = list(map(int, input().split()))
M = 10**9+7
# A.sort(reverse=True)

pos = []
neg = []

for a in A:
    if a > 0:
        pos.append(a)
    else:
        neg.append(a)


ans = 1

# print(K, K-len(pos)%2)
if ((K - len(pos)) % 2) != 0:
    #答えマイナスになる
    # pos.sort(reverse=True)
    neg.sort()
    # print(neg)
    neg = list(reversed(neg))
    print("neg2:", neg)

    for p in pos:
        ans *= p % M
        # ans *= p
    
    for n in neg[:K-len(pos)]:
        ans *= n % M
        # ans *= n
    # print("neg: ", ans)

    # while K > 0:
    #     if K >= 2 and len(neg) >= 2 and len(pos) >= 2:
    #         if neg[-1] * neg[-2] >= pos[-1] * pos[-2]:
    #             ans *= neg[-1] * neg[-2] % M
    #             neg.pop()
    #             neg.pop()
    #             K -= 2
    #         else:
    #             ans *= pos[-1] * pos[-2] % M
    #             pos.pop()
    #             pos.pop()
    #             K -= 2
    #     else:
    #         if K == 1:
    #             if len(pos) > 0:
    #                 ans *= pos[-1] %M               
    #             else:
    #                 ans *= neg[0] %M
    #             break
    #         else:
    #             #K<=2 or len(neg) < 2 or len(pos) < 2
    #             if len(pos) == 1 and len(neg) == 1:
    #                 ans *= pos[-1] %M
    #                 if K == 2:
    #                     ans *= neg[-1] %M
    #                     break
    #                 K -= 1
    #             elif len(pos) < 2:
    #                 ans *= neg[-1] * neg[-2] % M
    #                 neg.pop()
    #                 neg.pop()
    #                 K-= 2
    #             else:
    #                 #len(neg)が1
    #                 ans *= pos[-1] %M
    #                 pos.pop()
    #                 K -= 1

else:    
    pos.sort()
    neg.sort(reverse=True)

    while K > 0:
        if K >= 2 and len(neg) >= 2 and len(pos) >= 2:
            if neg[-1] * neg[-2] >= pos[-1] * pos[-2]:
                ans *= neg[-1] * neg[-2] % M
                neg.pop()
                neg.pop()
                K -= 2
            else:
                ans *= pos[-1] * pos[-2] % M
                pos.pop()
                pos.pop()
                K -= 2
        else:
            if K == 1:
                if len(pos) > 0:
                    ans *= pos[-1] %M               
                else:
                    ans *= neg[0] %M
                break
            else:
                #K<=2 or len(neg) < 2 or len(pos) < 2
                if len(pos) == 1 and len(neg) == 1:
                    ans *= pos[-1] %M
                    if K == 2:
                        ans *= neg[-1] %M
                        break
                    K -= 1
                elif len(pos) <= 1:
                    ans *= neg[-1] * neg[-2] % M
                    neg.pop()
                    neg.pop()
                    K-= 2
                else:
                    #len(neg)が1
                    ans *= pos[-1] %M
                    pos.pop()
                    K -= 1
                
print(ans%M)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
a = sorted(a, key = abs)[::-1]
ans = 1
hold = 0

if max(a) < 0:
    a = sorted(a)[::-1]
    for i in range(k):
        ans = ans*a[i]%(10**9 + 7)
    print(ans)
    exit()



for i in range(k - 1):
    if a[i] >= 0:
        ans = ans*a[i]%(10**9 + 7)
    else:
        if hold == 0:
            hold = a[i]
        else:
            ans = ans*a[i]*hold%(10**9 + 7)
            hold = 0

for j in range(k - 1, n):
    if a[j] < 0 and hold != 0:
        ans = ans*a[j]*hold%(10**9 + 7)
        print(ans)
        exit()
    elif a[j] >= 0:
        ans = ans*a[j]%(10**9 + 7)
        print(ans)
        exit()

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
import math
A = list(map(int,input().split()))
flag = 0
if 0 in A:
    flag = 1
A.sort()
plus = list(filter(lambda x:x>0, A))[::-1]
plus = list(map(lambda x:math.log(x),plus ))
from itertools import accumulate
acc_plu = [0] +  list(accumulate(plus))
minu = filter(lambda x:x<0, A)
minu = list(map(lambda x:math.log(-x),minu))
acc_min = [0] +  list(accumulate(minu))


if K % 2 == 0 : num = K // 2 + 1
else: num = (K + 1) // 2 
cand = []
x = K
y = 0
MOD = 10**9 +7
for i in range(num):
    try:
        cand.append((acc_plu[x] +  acc_min[y],x ,y ))
    except: pass
    x -= 2 
    y += 2


ans = 1
if cand == []:
    cnt = 0
    minu = list(filter(lambda x:x<0, A))
    for x in minu[::-1]:
        if cnt == K:break
        ans *= x
        ans %= MOD
        cnt += 1
    if flag:
        print(max(ans,0))
    else:
        print(ans)
else:
    cand = sorted(cand)[::-1]
    plus = list(filter(lambda x:x>0, A))[::-1]
    minu = list(filter(lambda x:x<0, A))
    c = cand[0]
    for i in range(c[1]):
        ans *= plus[i]
    for i in range(c[2]):
        ans *= minu[i]
    if flag:
        print(max(ans,0))
    else:
        print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import os
from sys import stdin, stdout

MOD = int(1e9+7)

def solve(tc):
    n, k = map(int, stdin.readline().split())
    seq = list(map(int, stdin.readline().split()))

    seq = sorted(seq, key=lambda x: abs(x), reverse=True)

    contain_zero = False
    last_plus = -1
    last_minus = -1
    mul_minus = False

    arr = []
    p = 0
    while p < n and len(arr) < k:
        if seq[p] == 0:
            contain_zero = True
            p += 1
            continue

        if seq[p] < 0:
            last_minus = len(arr)
            mul_minus ^= True
        elif seq[p] > 0:
            last_plus = len(arr)

        arr.append(seq[p])
        p += 1

    # should contain zeros
    if p == n and len(arr)<k:
        print(0)
        return

    # found maximal
    if not mul_minus:
        ans = 1
        for num in arr:
            ans *= num
            ans %= MOD
        print(ans)
        return

    first_plus = -1
    first_minus = -1
    while p < n:
        if seq[p]==0:
            contain_zero = True
            p += 1
            continue

        if seq[p] < 0:
            if first_minus < 0:
                first_minus = p
        elif seq[p] > 0:
            if first_plus < 0:
                first_plus = p
        p += 1

    if last_plus < 0 and first_plus < 0:
        if contain_zero:
            print(0)
        else:
            seq = sorted(seq)
            ans = 1
            for i in range(k):
                ans *= seq[i]
                ans %= MOD
            print(ans)
        return

    if first_minus < 0:
        arr[last_minus] = seq[first_plus]
    elif first_plus < 0:
        arr[last_plus] = seq[first_minus]
    else:
        if seq[first_plus]*arr[last_plus] < seq[first_minus]*arr[last_minus]:
            arr[last_plus] = seq[first_minus]
        else:
            arr[last_minus] = seq[first_plus]

    ans = 1
    for num in arr:
        ans *= num
        ans %= MOD
    print(ans)


tcs = 1
tc = 1
while tc <= tcs:
    solve(tc)
    tc += 1

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
ls = list(map(int,input().split()))
mod = 10**9+7
ls = sorted(ls,key=abs,reverse=True)

def mul(l,minp,minn):
  if minn==None:
    minn= -1
  if minp==None:
    minp= -1
  ans = 1
  
  for i in range(len(l)):
    if i==minn or i==minp:
      continue
    ans = ans*l[i]%mod
  return ans

if k%2==1:
  if n==sum([a<0 for a in ls]):
    print(mul(ls[n-k:],-1,-1))
    exit()
    

minn=None
minp=None
ncount= 0
for i in range(k):
  if ls[i]<0:
    minn=i
    ncount+=1
  else:
    minp=i

if ncount%2==0:
  print(mul(ls[:k],-1,-1))
  exit()
  
nextn=None
nextp=None
ind = k
while (nextn==None or nextp==None) and ind<n:
  if nextn==None and ls[ind]<0:
    nextn=ind
  if nextp==None and ls[ind]>0:
    nextp=ind
  
  ind+=1
if nextn==None:
  nextn =0
else:
  nextn = ls[nextn]
if nextp==None:
  nextp =0
else:
  nextp = ls[nextp]
  
  
v = max((ls[minn] if minn else 0)*nextn,(ls[minp] if minp else 0)*nextp)%mod
  
print(mul(ls[:k],minn,minp)*v%mod)

Submission status: Wrong Answer

Solution code:
n,k = map(int, input().split())
a = list(map(int, input().split()))
mod = 10**9+7
a1 = []
a2 = []
cnt = 0
for i in a:
    if (i >= 0):
        a1.append(i)
    else:
        a2.append(-i)
a1.sort()
a2.sort()
#print(a1,a2)
if (k==1):
    print(max(a)%mod)
    exit()
if (n==k):
    ans = 1
    for i in range(k):
        ans *= a[i]
        ans %= mod
    print(ans)
    exit()
if (len(a1)==0):
    if (k%2==0):
        ans = 1
        for i in range(k):
            ans *= a2.pop()
            ans %= mod
        print(ans)
        exit()
    else:
        ans = 1
        for i in range(k):
            ans *= -a2[i]
            ans %= mod
        print(ans)
        exit()
elif (len(a2)==0):
    ans = 1
    for i in range(k):
        ans *= a1.pop()
        ans %= mod
    print(ans)
    exit()

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

Submission status: Wrong Answer

Solution code:
n, k = (int(x) for x in input().split())
a = list(map(int, input().split()))
mod = pow(10,9)+7
a_po =[]
a_ne =[]
po = 0
ne = 0
for i in a:
	if i>=0:
		a_po.append(i)
	else:
		a_ne.append(i)
a_po.sort()
a_po.reverse()
a_ne.sort()
ans = 1
if len(a_po)==0 and k%2==1:
	a_ne.reverse()
	for i in range(k):
		ans*=a_ne[i]
	print((ans+mod)%mod)
else:
	if k%2==1:
		ans*=a_po.pop(0)
		k-=1
	for i in range(int(k/2)):
		if po*2>=len(a_po) and ne*2>=len(a_ne):
			su_po = a_po[2*po]*a_po[2*po+1]
			su_ne = a_ne[2*ne]*a_ne[2*ne+1]
			if su_po>su_ne:
				po+=1
				ans*=su_po
			else:
				ne+=1
				ans*=su_ne
		elif po*2>=len(a_po) and po*2<len(a_po):
			su_ne = a_ne[2*ne]*a_ne[2*ne+1]
			ans*=su_ne
			ne+=1
		elif po*2<len(a_po) and po*2>=len(a_po):
			su_po = a_po[2*po]*a_po[2*po+1]
			ans*=su_po
			po+=1
	print((ans+mod)%mod)

Submission status: Wrong Answer

Solution code:
import itertools
a, b = map(int, input().split())
A = sorted(map(int, input().split()))
long= list(itertools.combinations(A, b))
han=-99999999999999999

for a in long:
    goukei=1
    for b in a:
        goukei*=int(b)
        if goukei>=0:
            goukei%=1000000007
        else:
            continue
    if goukei>han:
        han=goukei

print(han)

Submission status: Wrong Answer

Solution code:
from functools import reduce
from collections import deque
def main():
    n, k = list(map(int, input().split()))
    A = list(map(int, input().split()))
    mod = 1000000007
    mul = lambda a:reduce(lambda x, y:x * y % mod, a, 1)
    p, m = 0, 0
    INF = float('inf')
    for a in A:
        if a > 0:
            p += 1
        elif a < 0:
            m += 1
    zero = n - (p + m)
    if k == 1:
        A.sort()
        print(A[-1] % mod)
    else:
        A.sort(key = lambda x: abs(x), reverse = True)
        if p == 0:
            if zero > 0:
                print(0)
            else:
                if k % 2 == 0:
                    A.sort(key = lambda x: abs(x), reverse = True)
                    print(mul(A[:k]))
                else:
                    A.sort(key = lambda x: abs(x), reverse = False)
                    print(mul(A[:k]))
        elif p == 1:
            if zero > 0:
                print(0)
            else:
                if k % 2 == 0:
                    A.sort()
                    print(mul(A[:k]))
                else:
                    A.sort()
                    print(mul(A[:k - 1]) * A[-1] % mod)
        else:
            if n - zero < k:
                print(0)
            else:
                A.sort(key = lambda x: abs(x), reverse = True)
                P, M = deque([]), deque([])
                for a in A:
                    if a > 0:
                        P.append(a)
                    elif a < 0:
                        M.append(a)
                ans = 1
                pp, mm = 0, 0
                if len(P) >= 2:
                    p0 = P.popleft()
                    p1 = P.popleft()
                    pp = p0 * p1
                else:
                    pp = -INF
                if len(M) >= 2:
                    m0 = M.popleft()
                    m1 = M.popleft()
                else:
                    mm = -INF
                while k >= 2:
                    if pp >= mm:
                        ans = ans * pp % mod
                        if len(P) >= 2:
                            p0 = P.popleft()
                            p1 = P.popleft()
                            pp = p0 * p1
                        else:
                            pp = -INF
                    else:
                        ans = ans * mm % mod
                        if len(M) >= 2:
                            m0 = M.popleft()
                            m1 = M.popleft()
                        else:
                            mm = -INF
                    k -= 2
                if k == 0:
                    print(ans % mod)
                else:
                    if len(P) > 0:
                        pp = P.popleft()
                        print(ans * pp % mod)
                    else:
                        A = list(filter(lambda x: x != 0, A))
                        print(mul(A[:-k:-1]))



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
L = list(map(int,input().split()))
mod = 10**9+7
for i in range(n):
    if L[i]<0:
        L[i] = -L[i]
L.sort(reverse = True)
sum1 =1
for i in range(m):
    sum1 *=L[i]%mod
if sum1<0:
    j = m-1
    while sum1<0:
        sumi//L[j]
    j -=1
print(sum1)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
po = sorted([ai for ai in a if ai > 0], reverse=True)
ne = sorted(ai for ai in a if ai < 0)
ze = 0 in a
mod = 10**9 + 7
c = 1
if len(po) == 0 or len(po) + len(ne) // 2 * 2 < k:
    if ze:
        print(0)
    else:
        for bi in sorted(po + ne, key=abs)[:k]:
            c = c * bi % mod
        print(c)
elif len(ne) < 2:
    for ai in sorted(a, reverse=True)[:k]:
        c = c * ai % mod
    print(c)
else:
    if len(po) >= k:
        pi = k - 1
        ni = -1
        pc = po[:k]
        nc = []
    else:
        if (k - len(po)) % 2:
            pi = len(po) - 2
            pc = po[:-1]
        else:
            pi = len(po) - 1
            pc = po
        ni = k - len(pc) - 1
        nc = ne[:k - len(pc)]
    for _ in range(min(len(pc), len(ne) - len(nc)) // 2):
        if ne[ni + 1] * ne[ni + 2] < po[pi - 1] * po[pi - 2]:
            break
        nc = nc + ne[ni + 1:ni + 3]
        pc = pc [:-2]
        ni += 2
        pi -= 2
    for pp in pc:
        c = c * pp % mod
    for nn in nc:
        c = c * nn % mod
    print(c)

Submission status: Wrong Answer

Solution code:
from collections import deque
CONST = 10**9 + 7
n, k = map(int,input().split())
a = list(map(int,input().split()))
a.sort()

if k == 1:
    print(a[-1] % CONST)
    exit()

a2 = deque(a)

mini = a2.popleft()
maxi = a2.pop()

if maxi < 0 or mini > 0:
    a2.appendleft(mini)
    ans = maxi % CONST
    for i in range(k-1):
        ans = (ans * a2.pop()) %CONST
    print(ans)
    exit()


ans = 1
ans2 = 1
for i in range(k-1):
    if len(a2) == 0:
        ans2 = (ans2 * maxi) % CONST
        ans2 = (ans2 * mini) % CONST
        print(ans)
        exit()

    if abs(mini) < abs(maxi):
        ans *= maxi
        ans2 = ans2 * maxi % CONST
        maxi = a2.pop()
    else:
        ans *= mini
        ans2 = ans2 * mini % CONST
        mini = a2.popleft()
if ans * maxi < ans * mini:
    print((ans2*mini)%CONST)
else:
    print((ans2*maxi)%CONST)

Submission status: Wrong Answer

Solution code:
N, K  = map(int, input().split())
A = list(map(lambda x: int(x)%(10**9+7), input().split()))
A.sort(reverse= True)
ans = 1
for i in range(K):
  ans = ans * A[i] % (10**9+7)
print(ans)

Submission status: Wrong Answer

Solution code:
import functools
import operator

prod = functools.partial(functools.reduce, operator.mul)


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

    a.sort(reverse=True)
    # if a[-1] >= 0:
    #     print(prod(a[:k]))
    #     return
    # if a[0] == 0:
    #     for i, _a in enumerate(a):
    #         if a[i] != 0:
    #             break
    #     else:
    #         print(0)
    #         return
    #     if k > len(a) - ind - 1:
    #         print(0)
    #         return
    #     if k % 2 == 1:
    #         print(0)
    #         return
    #     print(prod(a[len(a)-k:]))
    #     return
    
    left = 0
    right = len(a) - 1
    ret = 1
    i = 0
    while i < k:
        if i < k - 1:
            if a[left] * a[left+1] < a[right] * a[right-1]:
                ret *= a[right] * a[right-1]
                right -= 2
            else:
                ret *= a[left] * a[left+1]
                left += 2
            i += 2
        else:
            ret *= a[left]
            left += 1
            i += 1
        ret = ret % (10**9+7)
    print(ret)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys
# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 7)
from heapq import heappop, heappush
#from collections import OrderedDict, defaultdict
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
#from collections import deque
#import numba

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

    plus = [a for a in A if a >= 0]
    minus = [-a for a in A if a < 0]

    plus = sorted(plus, reverse=True)
    minus = sorted(minus, reverse=True)

    P, M  = [1], [1]
    for p in plus:
        P.append((P[-1] * p) % mod)
    for i, m in enumerate(minus):
        M.append(((-1) ** i) * (M[-1] * m) % mod)
    #print(P, M)


    max_ans = -1
    for i in range(0, K+1, 2):
        if i >= len(M) or K - i >= len(P):continue
        ans = M[i] * P[K-i] % mod
        if max_ans < ans:
            max_ans = ans
        #else:
        #    break

    if max_ans == -1:
        P, M = [1], [1]
        for p in plus[::-1]:
            P.append((P[-1] * p) % mod)
        for m in minus[::-1]:
            M.append(((-1) ** i) * (M[-1] * m) % mod)
        #print(P, M)

        for i in range(1, K + 1, 2):
            #print(i)
            if i >= len(M) or K - i >= len(P): continue
            ans = (-M[i] * P[K - i]) % mod
            #print(ans)
            if max_ans < ans:
                max_ans = ans

    print(max_ans)






if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
mod = 10 ** 9 + 7

N, K = map(int, input().split())
A = list(map(int, input().split()))
A.sort(key=lambda x: abs(x), reverse=True)
ans = 1
if len([v for v in A if v <= 0]) == N:
    for i in range(K):
        ans *= A[-(i + 1)]
        if abs(ans) > mod:
            ans %= mod
else:
    num_hu = len([v for v in A[:K] if v < 0])
    if num_hu % 2 == 0:
        for i in range(K):
            ans *= A[i]
            if abs(ans) > mod:
                ans %= mod
    else:
        if A[K - 1] < 0:
            if len([v for v in A[K:] if v > 0]):
                idx = K
                while True:
                    if A[idx] > 0:
                        break
                    idx += 1
                for i in range(K - 1):
                    ans *= A[i]
                    if abs(ans) > mod:
                        ans %= mod
                ans *= A[idx]
            elif len([v for v in A[K:] if v < 0]):
                idx = K - 2
                while True:
                    if A[idx] > 0:
                        break
                    idx -= 1
                for i in range(idx):
                    ans *= A[i]
                    if abs(ans) > mod:
                        ans %= mod
                ans *= A[K]
                for i in range(idx + 1, K):
                    ans *= A[i]
                    if abs(ans) > mod:
                        ans %= mod
            else:
                for i in range(K):
                    ans *= A[i]
                    if abs(ans) > mod:
                        ans %= mod
        elif A[K - 1] == 0:
            ans = 0
        else:
            if len([v for v in A[K:] if v < 0]):
                idx = K
                while True:
                    if A[idx] < 0:
                        break
                    idx += 1
                for i in range(K - 1):
                    ans *= A[i]
                    if abs(ans) > mod:
                        ans %= mod
                ans *= A[idx]
            elif len([v for v in A[K:] if v > 0]):
                idx = K - 2
                while True:
                    if A[idx] < 0:
                        break
                    idx -= 1
                for i in range(idx):
                    ans *= A[i]
                    if abs(ans) > mod:
                        ans %= mod
                ans *= A[K]
                for i in range(idx + 1, K):
                    ans *= A[i]
                    if abs(ans) > mod:
                        ans %= mod
            else:
                for i in range(K):
                    ans *= A[i]
                    if abs(ans) > mod:
                        ans %= mod
print(ans % mod)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
A=sorted(A, key=abs,reverse=True)
B=[0]*N
for i in range(N):
  if A[i]>=0:
    B[i]=1
  else:
    B[i]=-1

ans=1

p1=-1
for i in range(K):
  if B[i]==1:
    p1=i

p2=-1
for i in reversed(range(K,N)):
  if B[i]==1:
    p2=i

n1=-1
for i in range(K):
  if B[i]==-1:
    n1=i

n2=-1
for i in reversed(range(K,N)):
  if B[i]==-1:
    n2=i

if B[:K].count(-1)%2==0:
  for i in range(K):
    ans=(ans*A[i])%(10**9+7)
elif n1>=0 and p2>=0:
  if p1>=0 and n2>=0:
    if A[p2]/A[n1] >= A[n2]/A[p1]:
      for i in range(K):
        if i ==n1:
          ans=(ans*A[p2])%(10**9+7)
        else:
          ans=(ans*A[i])%(10**9+7)
    else:
      for i in range(K):
        if i ==p1:
          ans=(ans*A[n2])%(10**9+7)
        else:
          ans=(ans*A[i])%(10**9+7)
  else:
    for i in range(K):
      if i ==n1:
        ans=(ans*A[p2])%(10**9+7)
      else:
        ans=(ans*A[i])%(10**9+7)
elif p1>=0 and n2>=0:
  for i in range(K):
    if i ==p1:
      ans=(ans*A[n2])%(10**9+7)
    else:
      ans=(ans*A[i])%(10**9+7)
else:
  for i in range(K):
    ans=(ans*A[i])%(10**9+7)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2000)

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

mod = 10**9 + 7

als = []
test = True
for i in an:
    if i > 0:
        test = False
    als.append([abs(i), i])
if test and k % 2 == 1:
    an.sort(reverse=True)
    ans = 1
    for i in range(k):
        ans = ans * an[i] % mod
    print(ans)
    exit()

als.sort(reverse=True)

ans = 1
min_p = 10**9 + 1
min_m = - 10**9 + 1
cnt = 0
for i in range(k):
    x, y = als[i]
    ans = ans * x % mod
    if y > 0:
        min_p = x
    if y < 0:
        min_m = x
        cnt += 1

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

max_p = 0
max_m = 0
for j in range(k, n):
    if als[j][1] > 0:
        max_p = max(max_p, als[j][0])
    if als[j][1] < 0:
        max_m = max(max_m, als[j][0])
    if max_p != 0 and max_m != 0:
        break

def power(x, y):
    if   y == 0     : return 1
    elif y == 1     : return x % mod
    elif y % 2 == 0 : return power(x, y/2)**2 % mod
    else            : return power(x, y/2)**2 * x % mod

if max_m == 0 or max_p / min_m >= max_m / min_p:
    print(ans * max_p * power(min_m, mod-2) % mod)
else:
    print(ans * max_m * power(min_p, mod-2) % mod)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
minus_count=0
i=0
j=n-1
ans=1
count=0
MOD=(10**9)+7
#print(a)

if(a[j]<0 and k%2==1):
    for l in range(k):
        ans=((ans%MOD)*(a[j]%MOD))%MOD
        j-=1
else:
    while(count<k):
        if(count==k-1 and a[j]>0 and (abs(a[i]) > abs(a[j])) and minus_count%2==0 ):
            ans=((ans%MOD)*(a[j]%MOD))%MOD
            j-=1
        elif(a[i]==0 or a[j]==0):
            ans=0
            minus_count=0
            break
        elif(abs(a[i]) <= abs(a[j])):
            ans=((ans%MOD)*(a[j]%MOD))%MOD
            if(a[j]<0):
                minus_count+=1
            j-=1
        else:
            ans=((ans%MOD)*(a[i]%MOD))%MOD
            if(a[i]<0):
                minus_count+=1
            i+=1
#        print(i,j,ans)
        count+=1

print(ans)

Submission status: Wrong Answer

Solution code:
LIMIT = 1000000007
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))

A.sort(reverse=True)
resArray = A[:K]
if N == 1:
    print(resArray[0])
else:
    if(resArray[0] > 0):
        for i in range(1, int(K/2)+1):
            if abs(A[(-2 * i) + 1]) > resArray[-2] and abs(A[(-2 * i)]) > resArray[-1]:
                resArray = resArray[:-2]
                resArray.append(A[(-2 * i) + 1])
                resArray.append(A[(-2 * i) ])
                resArray.sort(reverse=True)
            else:
                break
res = 1
for i in resArray:
    res *= i 
    res = res % LIMIT
print(res)

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

maxList,minList = [],[]

list.sort(inList)
for i in range(k):
    minList.append(inList[i])
list.sort(inList, reverse=True)
for i in range(k):
    maxList.append(inList[i])
inList2 = minList+maxList

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

Submission status: Wrong Answer

Solution code:
"""    Arnab Chanda    """

from collections import defaultdict, deque
from itertools import permutations
from sys import stdin,stdout
from bisect import bisect_left, bisect_right
from copy import deepcopy
import heapq

int_input=lambda : int(stdin.readline())
string_input=lambda : stdin.readline().split()
multi_int_input =lambda : map(int, stdin.readline().split())
multi_input = lambda : stdin.readline().split()
list_input=lambda : list(map(int,stdin.readline().split()))
string_list_input=lambda: list(string_input())
MOD = pow(10,9)+7

n, k = multi_int_input()
arr = list_input()

def maxProductSubarrayOfSizeK(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 * A[i]) %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 * A[j])%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] * A[i + 1] )%MOD
  
        # product from right pointers 
        right_product = (A[j] * A[j - 1])%MOD 
  
        # Taking the max product from two  
        # choices. Correspondingly changing 
        # the pointer's position 
        if (left_product > right_product) : 
            product = (product * left_product)%MOD 
            i += 2
          
        else : 
            product = (product * right_product)%MOD
            j -= 2
  
    # Finally return product 

    return product%MOD


print(maxProductSubarrayOfSizeK(arr, n, k))