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:
import random
from collections import deque
import sys
n,k =map(int,input().split())
A=[int(i) for i in input().split()]
A.sort()
P=deque()
Q=deque()
for a in A:
    if a<0:
        P.append(a)
    else:
        Q.appendleft(a)
c=0
S=1
lim = 10**9+7

if len(Q) == 0 and k&1:
    for _ in range(k):
        S*=P.pop()
        S%=lim
    print(S)
    sys.exit()
    
while c < k:
    if len(P)>1:
        p = P[0]*P[1]
    elif len(P)==1:
        p = 0
    else:
        p = 0
        
    if len(Q)>1:
        q = Q[0]*Q[1]
    elif len(Q)==1:
        q = Q[0]
    else:
        q = 0
    #print(P,Q,p,q)  
    if p and q:
        if p<q or c == k-1:
            S*= Q.pop()
            S%= lim
            c+=1
        else:
            S*= P.pop()
            S%= lim
            S*= P.pop()
            S%= lim
            c+=2
    elif p and (not q):
        S*= P.pop()
        S%= lim
        S*= P.pop()
        S%= lim
        c+=2
    elif (not p) and q:
        S*= Q.popleft()
        S%= lim
        c+=1
    else:
        break
print(S)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N,K = IL()
A = IL()
A = sorted(A,key= lambda x:-abs(x))

if N==K:
  ans = 1
  for i in range(K):
    ans *= A[i]
    ans %= MOD
  print(ans)
  exit()

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

count_M = 0
last_M = None
last_P = None
for i in range(K):
  if A[i] < 0:
    last_M = i
    count_M += 1
  if A[i] >= 0:
    last_P = i

if count_M%2 == 0:
  ans = 1
  for i in range(K):
    ans *= A[i]
    ans %= MOD
  print(ans)
  exit()

else:
  ANS1 = -INF
  ANS2 = -INF
  if last_M!=None:
    for i in range(K,N):
      if A[i] >= 0:
        ans = 1
        for ii in range(K):
          if ii != last_M:
            ans *= A[ii]
            ans %= MOD
        ans *= A[i]
        ans %= MOD
        ANS1 = ans
        break
  if last_P!=None:
    for i in range(K,N):
      if A[i] < 0:
        ans = 1
        for ii in range(K):
          if ii != last_P:
            ans *= A[ii]
            ans %= MOD
        ans *= A[i]
        ans %= MOD
        ANS2 = ans
        break
  print(max(ANS1,ANS2))

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
lst=list(map(int,input().split()))
mod=10**9+7

plst=sorted([x for x in lst if x>=0],reverse=True)
nlst=sorted([abs(x) for x in lst if x<0],reverse=True)
out=[None for _ in range(k)]
lenn=len(nlst)
lenp=len(plst)



if lenp==0 and k%2==1:
    sm=1
    for i in range(lenn-1,lenn-k-1,-1):
        sm*=-nlst[i]
        sm%=mod
    print(sm)
    exit()


ptoken=0
ntoken=0
token=0
pm=0



while token<k:
    if ptoken==lenp:
        out[token]=nlst[ntoken]
        pm=(pm+1)%2
        ntoken+=1
    elif ntoken==lenn:
        out[token]=plst[ptoken]
        ptoken+=1
    elif plst[ptoken]>nlst[ntoken]:
        out[token]=plst[ptoken]
        ptoken+=1
    else :
        out[token]=nlst[ntoken]
        pm=(pm+1)%2
        ntoken+=1
    token+=1

if pm<0:
    if ptoken<lenp:
        out[-1]=plst[ptoken]
    else : 
        if n!=k :
            out[-1]=nlst[ntoken]


sm=1
for x in out:
    sm*=x
    sm%=mod

print(sm)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
li=list(map(int,input().split()))

plus=[]
minus=[]
zero=0

for i in li:
  if i>0:
    plus.append(i)
  elif i==0:
    zero+=1
  else:
    minus.append(abs(i))
plus.sort()
minus.sort()

#print(minus)

res=1

if K>N-zero:
  res=0
  
elif len(plus)==0:
  if K%2==1 and zero>0:
    res==0
  elif K%2==1:
    for i in range(K):

      res=(res*minus[i])
      res=res%(10**9+7)
    res=-res
  else:
      for i in range(K):
        res=(res*minus[-i])
        res=res%(10**9+7)
    
else:
  while K>1:
    if len(plus)>1 and len(minus)>1:
      if plus[-1]*plus[-2] > minus[-1]*minus[-2]:
          res=res*plus[-1]*plus[-2]
          del plus[-2:]
          K-=2
      else:
        res=res*minus[-1]*minus[-2]
        del minus[-2:]
        K-=2

    elif len(plus)<2 and len(minus)>=2:
      res=res*minus[-1]*minus[-2]
      del minus[-2:]
      K-=2
      
    elif len(plus)>=2 and len(minus)<2:
      res=res*plus[-1]*plus[-2]
      del plus[-2:]
      K-=2
    
    res=res%(10**9+7)
    
  if K==0:
    res=res
  elif len(plus)>0:
    res=res*plus[-1]
  else:
    res=res*minus[-1]*(-1)
  
print(res%(10**9+7))

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
mod = 10**9+7
a.sort()
mi = []
pl = []
if n == k:
    ans = 1
    for i in a:
        ans *= i
        ans %= mod
    print(ans)
    exit()
for i in a:
    if i < 0:
        mi.append(i)
    else:
        pl.append(i)
if pl == []:
    ans = 1
    count = 0
    if k%2:
        while count < k:
            ans *= a[-1-count]
            ans %= mod
            count += 1
    else:
        while count < k:
            ans *= a[count]
            ans %= mod
            count += 1
    print(ans)    
    exit()
pl = sorted(pl,reverse=True)
ip = 0
im = 0
if k%2:
    count = pl[0]
    k -= 1
    ip += 1
else:
    count = 1
while k > 0:
    if ip+2 <= len(pl):
        x = pl[ip]*pl[ip+1]    
    else:
        x = 1
    if im+2 <= len(mi):
        y = mi[im]*mi[im+1]
    else:
        y = 1
    if x >= y:
        ip += 2
        count = (x*count)%mod
    else:
        im += 2
        count = (y*count)%mod
    k -= 2

print(count%mod)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

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

    if N == K:
        ans = 1
        for i in range(N):
            ans *= A[i]
            ans %= MOD
        print(ans)
        return

    B = []
    all_m = True
    cnt_z = 0
    cnt_m = 0
    for a in A:
        if a > 0:
            B.append((a,1))
            all_m = False
        elif a < 0:
            B.append((a,-1))
            cnt_m += 1
        else:
            B.append((a,0))
            all_m = False
            cnt_z += 1
    
    if all_m:
        if K%2 == 1:
            ans = 1
            B.sort(key = lambda x:x[0],reverse = True)
            for i in range(K):
                ans *= B[i][0]
                ans %= MOD
            print(ans)
            return  
    
    B.sort(key = lambda x:abs(x[0]),reverse = True)
    ans = 1
    cnt_m = 0
    last_m = 1
    last_p = -1
    for i,(b,typ) in enumerate(B):
        if i >= K:
            break
        if typ == 0:
            ans = 0
            break
        elif typ > 0:
            ans *= b
            ans %= MOD
            last_p = b
        else:
            ans *= b
            ans %= MOD
            cnt_m += 1
            last_m = b

    if cnt_m%2 == 0 or ans == 0:
        print(ans)
    else:
        diff1 = last_p
        diff2 = -last_m
        inv1 = 1
        inv2 = 1

        find = False
        inv1 *= pow(last_m,MOD - 2,MOD)
        for j in range(K,N):
            if B[j][1] > 0:
                find = True
                diff1 *= B[j][0]
                inv1 *= B[j][0]
                inv1 %= MOD
                break

        inv2 *= pow(last_p,MOD - 2,MOD)
        for j in range(K,N):
            if B[j][1] < 0:
                find = True
                diff2 *= -B[j][0]
                inv2 *= B[j][0]
                inv2 %= MOD
                break
        if find:
            if diff1 > diff2:
                ans *= inv1
                ans %= MOD
            else:
                ans *= inv2
                ans %= MOD
        else:
            if B[-1][0] == 0:
                ans = 0
        print(ans)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import random
from collections import deque
import sys
n,k =map(int,input().split())
A=[int(i) for i in input().split()]
A.sort()
P=deque()
Q=deque()
for a in A:
    if a<0:
        P.append(a)
    else:
        Q.appendleft(a)
c=0
S=1
lim = 10**9+7

if len(Q) == 0 and k&1:
    for _ in range(k):
        S*=P.pop()
        S%=lim
    print(S)
    sys.exit()
    
while c < k:
    if len(P)>1:
        p = P[0]*P[1]
    elif len(P)==1:
        p = 0
    else:
        p = 0
        
    if len(Q)>1:
        q = Q[0]*Q[1]
    elif len(Q)==1:
        q = Q[0]
    else:
        q = 0
    #print(P,Q,p,q)  
    if p and q:
        if p<q or c == k-1:
            S*= Q.pop()
            S%= lim
            c+=1
        else:
            S*= P.pop()
            S%= lim
            S*= P.pop()
            S%= lim
            c+=2
    elif p and (not q):
        S*= P.pop()
        S%= lim
        S*= P.pop()
        S%= lim
        c+=2
    elif (not p) and q:
        S*= Q.pop()
        S%= lim
        c+=1
    else:
        break
print(S)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))
m = 10**9+7
pos = [*filter(lambda x: x >= 0, A)]
neg = [*filter(lambda x: x < 0, A)]
pos.sort(reverse=True)
neg.sort()

ans = 1
i,j = 0,0
while i+j < K:
    flag = True
    if i == len(pos):
        flag = False
    elif j == len(neg):
        flag = True
    elif pos[i] >= -neg[j]:
        flag = True
    else:
        flag = False

    if flag:
        ans = ans * pos[i] % m
        i += 1
    else:
        ans = ans * neg[j] % m
        j += 1
if j % 2 == 0 or N==K:
    print(ans)
elif len(pos) == 0:
    ans = 1
    for i in range(K):
        ans = ans * neg[len(neg)-1-i] % m
    print(ans)
else:
    flag = True
    if i >= len(pos)-1:
        flag = False
    elif j >= len(neg)-1:
        flag = True
    elif pos[i]*pos[i+1] >= neg[j]*neg[j+1]:
        flag = True
    else:
        flag = False

    # if flag:
    #     ans = ans * pow(neg[j],m-2,m) % m
    #     ans = ans * pos[i+1] % m
    # else:
    #     ans = ans * pow(pos[i],m-2,m) % m
    #     ans = ans * neg[j+1] % m
    print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
mod = 10**9+7
a.sort()
mi = []
pl = []

for i in a:
    if i < 0:
        mi.append(i)
    else:
        pl.append(i)
if pl == []:
    ans = 1
    count = 0
    if k%2:
        while count < k:
            ans *= a[-1-count]
            ans %= mod
            count += 1
    else:
        while count < k:
            ans *= a[count]
            ans %= mod
            count += 1
    print(ans)    
    exit()
pl = sorted(pl,reverse=True)
ip = 0
im = 0
if k%2:
    count = pl[0]
    k -= 1
    ip += 1
else:
    count = 1
while k > 0:
    check1 = True
    check2 = True
    if ip+2 <= len(pl):
        x = pl[ip]*pl[ip+1]    
    else:
        x = 1
        check1 = False
    if im+2 <= len(mi):
        y = mi[im]*mi[im+1]
    else:
        y = 1
        check2 = False
    if x > y or (check1 and not check2):
        ip += 2
        count = (x*count)%mod
    else:
        if check2:
            im += 2
            count = (y*count)%mod
    if check1 == False and check2 == False:
        break
    k -= 2

print(count%mod)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = sorted(list(map(int, input().split())), key = lambda x:-abs(x))
ans = 1
mod = 10 ** 9 + 7
sign = 1
flag = False
for i in range(k):
    if a[i] < 0:
        sign *= -1
    else:
        flag = True
if not flag or n == k:
    a = a[::-1]
    for i in range(k):
        ans *= a[i]
        ans %= mod
    print(ans)
else:
    if sign > 0:
        for i in range(k):
            ans *= a[i]
            ans %= mod
        print(ans)
    else:
        if a[k - 1] > 0:
            for i in range(k, n):
                if a[i] < 0:
                    a[k - 1], a[i] = a[i], a[k - 1]
        else:
            for i in range(k, n):
                if a[i] > 0:
                    a[k - 1], a[i] = a[i], a[k - 1]
        for i in range(k):
            ans *= a[i]
            ans %= mod
        print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappop, heappush
mod = 10**9+7
n, k = map(int, input().split())
a = [int(x) for x in input().split()]


def sgn(x):
    if x >= 0:
        return 0
    elif x < 0:
        return 1


pl = []
mn = []

for x in a:
    if x >= 0:
        pl.append(x)
    elif x < 0:
        mn.append(-x)

pl = sorted(pl, reverse=True)
mn = sorted(mn, reverse=True)


b = [(abs(a[i]), sgn(a[i])) for i in range(n)]
b = sorted(b, reverse=True)

c = [0, 0]
for i in range(k):
    c[b[i][1]] += 1


def solve(c):
    ans = 1
    for i in range(c[0]):
        ans *= pl[i]
        ans %= mod
    for i in range(c[1]):
        ans *= mn[i]
        ans %= mod
    return ans


if sum(c) == n:
    print(solve(c))
    exit()

if c[1] % 2 == 0:
    print(solve(c))
    exit()

if len(mn) == n and k % 2:
    tmp = 1
    for i in range(k):
        tmp *= mn[-i-1]
        tmp %= mod
    ans = -tmp
    print(ans % mod)
    exit()

ans = 0

if c[0] <= len(pl) - 1:
    c[0] += 1
    c[1] -= 1
    ans = solve(c)
    c[0] -= 1
    c[1] += 1

if 0 < c[0] and c[1] <= len(mn)-1:
    c[0] -= 1
    c[1] += 1
    ans = max(ans, solve(c))
    c[0] += 1
    c[1] -= 1

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def mod_div(x, y, mod=10 ** 9 + 7):
    return x * pow(y, mod - 2, mod) % mod


def solve():
    N, K = map(int, rl().split())
    A = list(map(int, rl().split()))
    MOD = 10 ** 9 + 7
    
    if K == N:
        ans = 1
        for ai in A:
            ans *= ai
            ans %= MOD
        print(ans)
        return

    A.sort(key=lambda num: abs(num), reverse=True)
    if all(ai < 0 for ai in A) and K % 2 == 1:
        ans = 1
        for ai in A[-K:]:
            ans *= ai
            ans %= MOD
        print(ans)
        return
    
    ans = 1
    min_pos, min_neg = 0, 0
    for ai in A[:K]:
        if ai < 0:
            min_neg = ai
        else:
            min_pos = ai
        ans *= ai
        ans %= MOD
    
    if 0 <= ans:
        print(ans)
    else:
        INF = 10 ** 10
        n_pos, n_neg = INF, INF
        for ai in A[K:]:
            if n_pos != INF and n_neg != INF:
                break
            if ai < 0 and n_neg == INF:
                n_neg = ai
            elif 0 <= ai and n_pos == INF:
                n_pos = ai
        if n_pos != INF and n_neg != INF:
            if abs(min_pos * n_pos) <= abs(min_neg * n_neg):
                ans = mod_div(ans, min_pos) * n_neg % MOD
            else:
                ans = mod_div(ans, min_neg) * n_pos % MOD
        elif n_pos != INF:
            ans = mod_div(ans, min_neg) * n_pos % MOD
        else:
            ans = mod_div(ans, min_pos) * n_neg % MOD
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
"""
    Satwik_Tiwari ;) .
    4th july , 2020  - Saturday
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase


import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
    ans = 1
    while(b>0):
        if(b%2==1):
            ans*=a
        a*=a
        b//=2
    return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
def bs(a,l,h,x):
    while(l<h):
        # print(l,h)
        mid = (l+h)//2
        if(a[mid] == x):
            return mid
        if(a[mid] < x):
            l = mid+1
        else:
            h = mid
    return l

def sieve(a): #O(n loglogn) nearly linear
    #all odd mark 1
    for i in range(3,((10**6)+1),2):
        a[i] = 1
    #marking multiples of i form i*i 0. they are nt prime
    for i in range(3,((10**6)+1),2):
        for j in range(i*i,((10**6)+1),i):
            a[j] = 0
    a[2] = 1 #special left case
    return (a)


def bfs(g,st):
    visited = [-1]*(len(g))
    visited[st] = 0
    queue = []
    queue.append(st)
    new = []
    while(len(queue) != 0):
        s = queue.pop()
        new.append(s)
        for i in g[s]:
            if(visited[i] == -1):
                visited[i] = visited[s]+1
                queue.append(i)
    return visited


def dfsusingstack(v,st):
    d = deque([])
    visited = [0]*(len(v))
    d.append(st)
    new = []
    visited[st] = 1
    while(len(d) != 0):
        curr = d.pop()
        new.append(curr)
        for i in v[curr]:
            if(visited[i] == 0):
                visited[i] = 1
                d.append(i)
    return new


def solve():
    n,k =sep()
    a = lis()
    pos= []
    neg = []
    for i in range(n):
        if(a[i]>=0):
            pos.append(a[i])
        else:
            neg.append(a[i])
    pos = sorted(pos)[::-1]
    neg = sorted(neg)[::-1]
    cnt = k
    st1 = 0
    st2 = 0
    ans = 1
    while(cnt>0):
        if(cnt>1):
            if(st1>=len(pos)-1 and st2>=len(neg)-1):
                ans = (ans*((neg[st2]*pos[st1])%mod))%mod
                st1+=1
                st2+=1
                cnt-=2
                continue
            if(st1>=len(pos)-1):
                ans = (ans*((neg[st2]*neg[st2+1])%mod))%mod
                st2+=2
                cnt-=2
                continue
            if(st2>=len(neg)-1):
                ans = (ans*((pos[st1]*pos[st1+1])%mod))%mod
                st1+=2
                cnt-=2
                continue
            if(cnt==3 and st1 == len(pos)-2):
                ans = (ans*((neg[st2]*neg[st2+1])%mod))%mod
                st2+=2
                cnt-=2
                continue
            if(pos[st1]*pos[st1+1] > neg[st2]*neg[st2+1]):
                ans = (ans*((pos[st1]*pos[st1+1])%mod))%mod
                st1+=2
                cnt-=2
            else:
                ans = (ans*((neg[st2]*neg[st2+1])%mod))%mod
                st2+=2
                cnt-=2
        else:
            if(st1>len(pos)-1):
                ans = (ans*neg[st2])%mod
                st2+=1
                cnt-=1
                continue
            ans = (ans*pos[st1])%mod
            st1+=1
            cnt-=1
    print(ans%mod)





testcase(1)
# testcase(int(inp()))

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
mod = 10**9+7
a.sort()
mi = []
pl = []

for i in a:
    if i < 0:
        mi.append(i)
    else:
        pl.append(i)
if pl == []:
    ans = 1
    count = 0
    if k%2:
        while count < k:
            ans *= a[-1-count]
            ans %= mod
            count += 1
    else:
        while count < k:
            ans *= a[count]
            ans %= mod
            count += 1
    print(ans)    
    exit()
pl = sorted(pl,reverse=True)
ip = 0
im = 0
if k%2:
    count = pl[0]
    k -= 1
    ip += 1
else:
    count = 1
while k > 0:
    check1 = True
    check2 = True
    if ip+2 <= len(pl):
        x = pl[ip]*pl[ip+1]    
    else:
        x = 1
        check1 = False
    if im+2 <= len(mi):
        y = mi[im]*mi[im+1]
    else:
        y = 1
        check2 = False
    if x > y or check1 and not check2:
        ip += 2
        count = (x*count)%mod
    else:
        if check2:
            im += 2
            count = (y*count)%mod
    if check1 == False and check2 == False:
        break
    k -= 2

print(count%mod)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
li=list(map(int,input().split()))

plus=[]
minus=[]
zero=0

for i in li:
  if i>0:
    plus.append(i)
  elif i==0:
    zero+=1
  else:
    minus.append(abs(i))
plus.sort()
minus.sort()

#print(minus)

res=1

if K>N-zero:
  res=0
  
elif len(plus)==0:
  if K%2==1 and zero>0:
    res==0
  else:
    for i in range(K):

      res=(res*minus[i])
      res=res%(10**9+7)
    res=-res
    
else:
  while K>1:
    if len(plus)>1 and len(minus)>1:
      if plus[-1]*plus[-2] > minus[-1]*minus[-2]:
          res=res*plus[-1]*plus[-2]
          del plus[-2:]
          K-=2
      else:
        res=res*minus[-1]*minus[-2]
        del minus[-2:]
        K-=2

    elif len(plus)<2 and len(minus)>=2:
      res=res*minus[-1]*minus[-2]
      del minus[-2:]
      K-=2
      
    elif len(plus)>=2 and len(minus)<2:
      res=res*plus[-1]*plus[-2]
      del plus[-2:]
      K-=2
    
    res=res%(10**9+7)
    
  if K==0:
    res=res
  elif len(plus)>0:
    res=res*plus[-1]
  else:
    res=res*minus[-1]*(-1)
  
print(res%(10**9+7))

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
MOD=10**9+7
p=[]
n=[]
for i in range(N):
    if A[i]<0:
        n.append(A[i])
    else:
        p.append(A[i])
p.sort(reverse=True)
n.sort()
numplus=len(p)
if numplus==0:
    ans=1
    if K%2==1:
        for i in range(1,K+1):
            ans=(ans*n[i*(-1)])%MOD
    else:
        for i in range(K):
            ans=(ans*n[i])%MOD
elif N==K:
    ans=1
    for i in range(N):
        ans=(ans*A[i])%MOD
else:
    if numplus>=K:
        x=K
        if 0 in p:
            zero=p.index(0)
            len(p)-zero-1
    else:
        if (K-numplus)%2==1:
            x=numplus-1
        else:
            x=numplus
    ans=1
    for i in range(x):
        ans=(ans*p[i])%MOD
    for i in range(K-x):
        ans=(ans*n[i])%MOD
    temp=ans
    while x>1:
        if len(n)<(K-x+2):
            break
        if n[K-x]*n[K-x+1]<p[x-1]*p[x-2]:
            break
        temp=(temp*n[K-x]*n[K-x+1])%MOD
        temp=(temp*pow(p[x-1]*p[x-2],MOD-2,MOD))%MOD
        ans=temp
        x-=2
print(ans)