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

mainasu=[]
purasu=[]
zero=[]
for aa in a:
    if aa==0:
        zero.append(aa)
    elif aa>0:
        purasu.append(aa)
    else:
        mainasu.append(aa*(-1))

#ゼロを選ばないといけない絶対ゼロ
if len(purasu)+len(mainasu)<k:
    print(0)
    exit()
mod=10**9+7

#プラスがない
if len(purasu)==0:
    #奇数個選択しないといけない
    if k%2==1:
        if len(zero)>0:
            print(0)
            exit()
        else:
            mainasu.sort()
            cnt=0
            ans=1
            while cnt<k:
                ans=ans*mainasu[cnt]%mod
                cnt+=1
            ans=abs(ans-mod)
    #偶数個選択可能
    else:
        if len(mainasu)%2==0:
            mainasu.sort(reverse=True)
            cnt=0
            ans=1
            while cnt<k:
                ans=ans*mainasu[cnt]%mod
                cnt+=1
        else:
            print(0)
            exit()
    print(ans%mod)
    exit()


purasu.sort(reverse=True)
mainasu.sort(reverse=True)

p_pos=0
m_pos=0
cnt=0
ans=1
while cnt<k:
    #マイナスもプラスも選択可能
    #print(">>",cnt)
    if p_pos<len(purasu) and m_pos+1<len(mainasu):
        #print("1")
        #ラスト1個しか選べない
        if cnt==k-1:
            ans=ans*purasu[p_pos]
            ans=ans%mod
            cnt+=1
            p_pos+=1
        #複数個選べる
        else:
            #マイナスの方が大きい
            if purasu[p_pos]<=mainasu[m_pos+1] or cnt<k-2:
                tmp=(mainasu[m_pos]%mod)*(mainasu[m_pos+1]%mod)
                tmp=tmp%mod
                ans=ans*tmp
                ans=ans%mod
                m_pos+=2
                cnt+=2
            else:
                ans=ans*purasu[p_pos]
                ans=ans%mod
                cnt+=1
                p_pos+=1

    #プラスのみ選べる
    elif p_pos<len(purasu):
        #print("2>>",len(purasu),p_pos)
        ans=ans*purasu[p_pos]
        ans=ans%mod
        cnt+=1
        p_pos+=1

    #マイナスのみ2個選べる
    elif m_pos+1<len(mainasu) and cnt+1<k:
        #print("3")
        tmp=(mainasu[m_pos]%mod)*(mainasu[m_pos+1]%mod)
        tmp=tmp%mod
        ans=ans*tmp
        ans=ans%mod
        m_pos+=2
        cnt+=2
    #マイナスのみ1個選べる
    elif m_pos<len(mainasu):
        #print("4")
        #ゼロがある
        if len(zero)>0:
            print(0)
            exit()
        else:
            ans=ans*mainasu[m_pos]*(-1)
            #print("mainasu",ans)
            m_pos+=1
            cnt+=1
    #print(ans)

print(ans%mod)

Submission status: Wrong Answer

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

ps = []
ns = []
zs = []
for i in range(n):
  if a[i] > 0:
    ps.append(a[i])
  elif a[i] < 0:
    ns.append(a[i])
  else:
    zs.append(a[i])
  
if k == 1:
  print(max(a))
elif len(ps) + len(ns) < k:
  print(0)
elif len(ps) == 0:
  ans = 1
  if k % 2 == 0:
    ns = sorted(ns)
    for i in range(k):
      ans = ans * ns[i] % mod
  elif len(zs) > 0:
    print(0)
  else:
    ns = sorted(ns, reverse=True)
    for i in range(k):
      ans = ans * ns[i] % mod
  print(ans)
else:
  ans = 1
  ps = sorted(ps, reverse=True)
  ns = sorted(ns)
  if k % 2 == 0:
    pp = []
    for i in range(0,min(k, len(ps)), 2):
      try:
        pp.append(ps[i] * ps[i+1])
      except:
        pass
  else:
    pp = []
    ans = ps[0]
    for i in range(1,len(ps), 2):
      try:
        pp.append(ps[i] * ps[i+1])
      except:
        pass
  np = []
  for i in range(0, len(ns), 2):
    try:
      np.append(ns[i] * ns[i+1])
    except:
      pass
  pnp = sorted(pp + np, reverse=True)
  if len(pnp) >= k//2:
    for i in range(k//2):
      ans = ans * pnp[i] % mod
    print(ans)
  else:
    print(0)

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    _LI = lambda : [-int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()
    DD = ((1,0),(0,1),(-1,0),(0,-1))

    N,K = LI()
    A = LI()

    ans = 1
    ma = max(A)
    if ma <= 0 and K % 2:
        x = sorted(A,reverse=True)
        for i in range(K):
            ans = (ans * A[i]) % MOD
        print(ans)
        return

    x = sorted(A, key=lambda x: abs(x), reverse=True)
    m = 0
    for i in range(K):
        ans = (ans * x[i]) % MOD
        if x[i] < 0 :m += 1

    if K == N or m % 2 == 0:
        print(ans)
        return
    if x[K] == 0:
        print(0)
        return
    if m == K:
        ans = (ans * pow(x[K-1],MOD-2,MOD) * max(x[K:])) % MOD

    else:
        K1 = -1
        for i in range(K+1,N):
            if x[K] * x[i] < 0:
                K1 = i
                break

        f1 = 0.0
        f2 = 0.0
        i0 = -1
        i1 = -1
        for i in range(K-1,-1,-1):
            if x[i] * x[K] < 0:
                i0 = i
                f1 = x[K] / x[i]
                break

        if K1 >= 0:
            for i in range(K-1,-1,-1):
                if x[i] * x[K1] < 0:
                    i1 = i
                    f2 = x[K1] / x[i]
                    break

        if abs(f1) >= abs(f2) or  i1 < 0:
            ans = (ans * pow(x[i0],MOD-2,MOD) * x[K]) % MOD
        else:
            ans = (ans * pow(x[i1],MOD-2,MOD) * x[K1]) % MOD

        print(ans)
        return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left, bisect_right

mod = 10 ** 9 + 7
n, k = map(int, input().split())
A = list(map(int, input().split()))
# dp = [[[0] * (2) for _ in range(k+1)]for _ in range(n+1)]
# # dp[桁][数][負数の数=1,0]

A.sort()
n_minus = bisect_left(A, 0)
n_zero = bisect_right(A, 0) - n_minus
n_plus = n - n_minus - n_zero

possible_max = min(k, n_minus)
possible_min = max(k - (n_plus + n_zero), 0)
ans = 1
if possible_max == possible_min and possible_min % 2 == 1:
    if k - (possible_min) > 0 and n_zero > 0:
        print(0)
        exit()
    A_plus = A[n - (n_plus) :]
    A_minus = A[:n_minus]
    A_minus.sort(reverse=True)
    # 負の数は奇数個小さい方から選ぶ
    for i in range(possible_min):
        ans *= A_minus[i]
        ans %= mod
    for i in range(k - possible_min):
        ans *= A_plus[i]
        ans %= mod
else:
    # 正の数に成る→大きいものがほしい
    # 負の数は偶数個、これの数を決め打つ
    # 計算すると大変だから大小を考える

    A_plus = A[n - (n_plus) :]
    A_plus.sort(reverse=True)
    A_minus = A[:n_minus]

    # 負の数を使う数を決め打つ
    # 最終的に正にできるパターン
    minus_num_max = min(n_minus // 2, k // 2)
    select = k - 2 * minus_num_max
    if n_plus < select:
        print(0)
        exit()
    # 負の数にしかできないパターン
    # 遊びがない時に奇数個の負の数を選ばざるを得ない
    # その時に0があるかどうかパターン
    kouho = []
    for i in range(minus_num_max):
        if 2 * i + 1 >= n_minus:
            break
        temp = A_minus[2 * i] * A_minus[2 * i + 1]
        kouho.append((temp, -1))
    for i in range(n_plus // 2):
        temp = A_plus[2 * i] * A_plus[2 * i + 1]
        kouho.append((temp, +1))
    kouho.sort(reverse=True)
    if k % 2 == 0:
        for i in range(k // 2):
            ans *= kouho[i][0]
            ans %= mod
    else:
        cnt = 0
        i = 0
        for i in range(k // 2):
            num, f = kouho[i]
            if f == 1:
                cnt += 1
            ans *= num
            ans %= mod
        if n_plus<=2*cnt:
            print(ans)
            exit()
        ans *= A_plus[2 * cnt]
        ans %= mod


print(ans % mod)

Submission status: Wrong Answer

Solution code:
N, K, *A = map(int, open(0).read().split())
MOD = 10 ** 9 + 7

if sum(v == 0 for v in A) > N - K:
    print(0)
    exit()

p_num = sum(v > 0 for v in A)
z_num = sum(v == 0 for v in A)
m_num = sum(v < 0 for v in A)
if p_num < K and m_num > 0 and z_num > 0:
    print(0)
    exit()
if all(v <= 0 for v in A):
    if K % 2 == 1 and any(v == 0 for v in A):
        print(0)
        exit()
    x = sorted([v for v in A if v < 0])
    ans = 1
    if K % 2 == 0:
        for i in range(K):
            ans = ans * x[i] % MOD
    else:
        n = len(x)
        for i in range(n - K, n):
            ans = ans * x[i] % MOD

    print(ans)
    exit()


x = sorted([(abs(v), v // abs(v)) for v in A if v != 0])
plus = []
minus = []
for i in range(K):
    v, s = x.pop()
    if s == 1:
        plus.append(v)
    else:
        minus.append(v)


if len(minus) % 2 != 0:
    p_cand = MOD
    m_cand = MOD
    while x:
        v, s = x.pop()
        if s == 1 and p_cand == MOD:
            p_cand = v
        elif s == -1 and m_cand == MOD:
            m_cand = v

    if p_cand == MOD and m_cand != MOD and plus:
        plus.pop()
        minus.append(m_cand)
    elif m_cand == MOD and p_cand != MOD and minus:
        minus.pop()
        plus.append(p_cand)
    elif p_cand != MOD and m_cand != MOD and plus and minus:
        p_org = plus.pop()
        m_org = minus.pop()
        if p_org * p_cand > m_org * m_cand:
            plus.append(p_org)
            plus.append(p_cand)
        else:
            minus.append(m_org)
            minus.append(m_cand)


ans = 1
for v in plus:
    ans = ans * v % MOD
for v in minus:
    ans = ans * (-v) % MOD
print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy
import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]

######################################################################################################
def zenkake(K):
    num=1
    for a in K:
        num*=(mod+a)
        num%=mod
    return num
n,k=inputintlist()
A=inputintlist()
A.sort()


ans=-inf
#負の数を偶数個選ぶ
S=[]
F=[]
for a in A:
    if a<0:
        F.append(a)
    else:
        S.append(a)
S.reverse()
S.append(-1)
F.append(1)
fcnt=0
scnt=0
i=0
j=0
kakeru=[]
for a in range(k):
    if -F[i]<S[j]:
        kakeru.append(S[j])
        j+=1
        scnt+=1
    else:
        kakeru.append(F[i])
        i+=1
        fcnt+=1
S.pop()
F.pop()
if fcnt%2==0:
    ans=max(ans,zenkake(kakeru))
else:
    if len(S)>0 and fcnt>0 and scnt>0:
        if fcnt==len(F) and scnt==len(S):
            pass
        elif fcnt==len(F):
            kakeru.append(S[scnt])
            kakeru[kakeru.index(F[fcnt-1])]=1
            ans=max(ans,zenkake(kakeru))
        elif scnt==len(S):
            kakeru.append(F[fcnt])
            kakeru[kakeru.index(S[scnt-1])]=1
            ans=max(ans,zenkake(kakeru))
        else:
            if -F[fcnt]<S[scnt]:
                kakeru.append(S[scnt])
                kakeru[kakeru.index(F[fcnt-1])]=1
            else:
                kakeru.append(F[fcnt])
                kakeru[kakeru.index(S[scnt-1])]=1
            ans=max(ans,zenkake(kakeru))
if ans==-inf:
    #負の数を奇数個
    S=[]
    F=[]
    for a in A:
        if a<0:
            F.append(a)
        else:
            S.append(a)
    S.reverse()
    F.reverse()
    if len(S)>=k:
        ans=max(ans,zenkake(S[:k]))
    else:
        num=zenkake(S[:k])
        k-=len(S)
        if k%2==1:
            for a in range(k):
                num*=(F[a]+mod)
                num%=mod
        ans=max(ans,num)
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()]

pl = []
mn = []
zr = []

tmp = 1
cnt = 0

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

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

ans = 0

if len(mn) >= k and k % 2:
    tmp = 1
    for i in range(1, k+1):
        tmp *= mn[-i]
        tmp %= mod
    ans = -tmp

if len(pl) == 0 and len(mn) >= k:
    tmp = 1
    for i in range(1, k+1):
        tmp *= mn[-i]
        tmp %= mod
    ans = -tmp
    print(ans % mod)
    exit()

if len(zr) > 0:
    ans = max(0, ans)

pl_cum = [1]
for i, x in enumerate(pl):
    pl_cum.append(pl_cum[-1]*x % mod)

mn_cum = [1]
for i, x in enumerate(mn):
    mn_cum.append(mn_cum[-1]*x % mod)


for p in range(0, k+1, 2):
    if len(mn) < p:
        break
    first = False
    if len(pl) >= k-p:
        first = True
        pl_ind = k-p
        mn_ind = p
        break

if not first:
    print(ans % mod)
    exit()

while pl_ind-2 > -1 and mn_ind+1 < len(mn):
    if pl[pl_ind-1]*pl[pl_ind-2] <= mn[mn_ind]*mn[mn_ind+1]:
        pl_ind -= 2
        mn_ind += 2
    else:
        break

if pl_ind < 0:
    ans = mn_cum[mn_ind]
else:
    ans = pl_cum[pl_ind]*mn_cum[mn_ind]

print(ans % mod)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
mod = 10**9 + 7
b_p = []
b_n = []
ab = []
for i in range(n):
    ab.append([abs(a[i]), a[i]])
    if a[i] >= 0:
        b_p.append(a[i])
    else:
        b_n.append(a[i])
b_p = sorted(b_p,reverse=True)
b_n = sorted(b_n)
ab.sort(key= lambda val : val[0])
ans = 1
i = 0
x = 0
y = 0
if k%2 == 1:
    if len(b_p) >= 1:
        ans *= b_p[0]
        x += 1
        i += 1
while i <= k-1:
    i += 2
    if x < len(b_p)-1 and y < len(b_n)-1:
        if b_p[x]*b_p[x+1] > b_n[y]*b_n[y+1]:
            ans *= b_p[x]*b_p[x+1]
            ans %= mod
            x += 2
        else:
            ans *= b_n[y]*b_n[y+1]
            ans %= mod
            y += 2
    
    elif x < len(b_p)-1:
        ans *= b_p[x]*b_p[x+1]
        ans %= mod
        x += 2
    elif y < len(b_n)-1:
        ans *= b_n[y]*b_n[y+1]
        ans %= mod
        y += 2
    
if i != k:
    if 0 in b_p:
        ans = 0
    else:
        ans = 1
        for i in range(k):
            ans *= ab[i][1]
            ans %= mod
        
print(ans%mod)

Submission status: Wrong Answer

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

zeros = []
pluss = []
minuss = []

for i in range(N):
    if A[i]>0:
        pluss.append(A[i])
    elif A[i]==0:
        zeros.append(A[i])
    else:
        minuss.append(A[i])

pluss = sorted(pluss, reverse = True)
minuss = sorted(minuss)


if len(pluss) + (min(len(minuss), K)//2)*2 >= K:
    answer_type = 1
elif len(zeros) > 0:
    answer_type = 2
else:
    answer_type = 3

rest = K
if answer_type == 1:
    plus_now = 0
    minus_now = 0
    minus_counter = 0
    answer = 1
    for i in range(K):
        if plus_now < len(pluss):
            plus_target = pluss[plus_now]
        else:
            plus_target = -1000000000000
        
        if minus_now < len(minuss):
            minus_target = minuss[minus_now]
        else:
            minus_target = 1000000000000
        
        if plus_target >= -minus_target:
            answer = (answer*plus_target)%mod
            plus_now += 1
        else:
            answer = (answer*minus_target)%mod
            minus_now += 1
            minus_counter += 1
    
    if minus_counter%2 == 1:
        if minus_now >= len(minuss):
        
            answer = answer * pow(minuss[minus_now-1],mod-2,mod)
            answer = answer * pluss[plus_now]
        elif plus_now >= len(pluss):
            answer = answer * pow(pluss[plus_now-1],mod-2,mod)
            answer = answer * minuss[minus_now]
        elif pluss[plus_now]/(-1*minuss[minus_now-1]) > -1*minuss[minus_now]/(-1*pluss[plus_now-1]):
            answer = answer * pow(minuss[minus_now-1],mod-2,mod)
            answer = answer * pluss[plus_now]

elif answer_type == 2:
    answer = 0
elif answer_type == 3:
    minuss = sorted(minuss, reverse = True)
    pluss = sorted(pluss, reverse = True)
    plus_now = 0
    minus_now = 0
    answer = 1
    for i in range(K):
        if plus_now < len(pluss):
            plus_target = pluss[plus_now]
        else:
            plus_target = 10000000000000
        
        if minus_now < len(minuss):
            minus_target = minuss[minus_now]
        else:
            minus_target = -1000000000000  
        
        if plus_target <= -minus_target:
            answer = (answer*plus_target)%mod
            plus_now += 1
        else:
            answer = (answer*minus_target)%mod
            minus_now += 1
print(answer%mod)

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split())
A = list(map(int,input().split()))
BIG = 10**9 + 7
A.sort()
A = A[::-1]
B = [-1 * item for item in A]

import heapq
ans = 1
if K%2 == 1:
    for i in range(K):
        ans = (ans * A[i])
        ans = ans%BIG
    print(ans%BIG)
else:
    heapq.heapify(A)
    heapq.heapify(B)
    for i in range(K//2):
        a = heapq.heappop(A)
        b = heapq.heappop(A)
        c = heapq.heappop(B)
        d = heapq.heappop(B)
        if a*b > c*d:
            heapq.heappush(B,c)
            heapq.heappush(B,d)
            ans = ans * a
            ans = ans%BIG
            ans = ans * b
            ans = ans%BIG
        else:
            heapq.heappush(A,a)
            heapq.heappush(B,b)
            ans = ans*c
            ans = ans%BIG
            ans = ans*d
            ans = ans%BIG
    print(ans)

Submission status: Wrong Answer

Solution code:
def resolve():
    N,K = map(int,input().split())
    A = list(map(int,input().split()))
    pls = [i for i in A if i > 0]
    ms = [i for i in A if i <0]
    pls.sort(reverse=True)
    ms.sort(reverse=False)
    A.sort(key = lambda x : abs(x),reverse=True)
    if len(pls)+len(ms) < K:
        print(0)
        return
    if len(pls) == 0 and K %2 == 1:
        if len(ms) != N:
            print(0)
            return
        x=1
        for i in list(reversed(ms))[:K]:
            x*= abs(i)
            x%= 10**9+7

        print((-x)%(10**9+7))
        return
    if len(pls)+len(ms) == K and K %2==1:
        if K ==N:
            print(0)
            return

        result=1
        for i in pls:
            result*=i
            result%=10**9+7
        for i in ms:
            result*=abs(i)
            result%=10**9+7
        print(result%(10**9+7))
        return
    pc = 0
    mc = 0
    for i in range(K):
        if pc >= len(pls):
            mc+=1
        elif mc >= len(ms):
            pc+=1
        elif pls[pc] > abs(ms[mc]):
            pc +=1
        else:
            mc +=1

    if mc%2  !=0:
        aplan=0
        bplan=0
        if mc < len(ms)-1:
            aplan = abs(ms[mc] *ms[mc-1])
        if pc < len(pls)-1:
            bplan = abs(pls[pc]*pls[pc-1])
        
        if aplan>bplan:
            pc -=1
            mc +=1
        else:
            pc +=1
            mc -=1
    result=1
    for i in pls[:pc]:
        result*=i
        result%=10**9+7
    for i in ms[:mc]:
        result*=abs(i)
        result%=10**9+7
    print(result)


resolve()

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
mod = 10**9 + 7
plus = []
minus = []
zlen = 0
for i in map(int, input().split()):
    if i >= 0:
        plus.append(i)
    elif i < 0:
        minus.append(i)
    else:
        zlen += 1
plen = len(plus)
mlen = len(minus)
# if K > plen + mlen:
#     print(0)
#     import sys
#     sys.exit()
plus.sort(reverse=True)
minus.sort()
pp = [1]
mp = [1]
for p in plus:
    pp.append((pp[-1]*p)%mod)
for m in minus:
    mp.append((mp[-1]*(-m))%mod)
ppm = [1]
mpm = [1]
for p in plus[::-1]:
    ppm.append((ppm[-1]*p)%mod)
for m in minus[::-1]:
    mpm.append((mpm[-1]*(-m))%mod)
ans = -float("inf")
ans_m = float("inf")
# kこマイナスから選ぶ
for k in range(K+1):
    if mlen < k:
        continue
    if plen < K-k:
        continue
    # 最大を目指す
    if k % 2 == 0:
        tmp = mp[k] * pp[K-k]
        ans = max(ans, tmp)
    # 絶対値最小を目指す
    else:
        tmp = mpm[k] * ppm[K-k]
        ans_m = min(ans_m, tmp)
if ans == -float("inf"):
    ans = -ans_m
# if ans < 0 and zlen > 0:
#     print(0)
#     import sys
#     sys.exit()
print(ans%mod)

Submission status: Wrong Answer

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

mod = 10**9+7

prod = 1

if K % 2 == 0:
    for i in range(N):
        A[i] = abs(A[i])
    
    list.sort(A, reverse=True)

    for i in range(K):
        prod *= A[i]
        prod = prod % mod
else:    
    list.sort(A, reverse=True)

    for i in range(K):
        prod *= A[i]
        prod = prod % mod

print(prod)

Submission status: Wrong Answer

Solution code:
import heapq
mod = 10**9+7
N,K = map(int, input().split())
A = list(map(int, input().split()))
P = []
M = []
for a in A:
    if a > 0:
        P.append(-a)
    else:
        M.append(a) 
A.sort(reverse=True)
heapq.heapify(P)
heapq.heapify(M)
ans2 = 1
i = 0
while i < K:
    i += 1
    if(len(P)>=2 and len(M)>=2):
        i +=1
        if(P[0]*P[1]<M[0]*M[1]):
            ans2 = ans2*(heapq.heappop(M)*heapq.heappop(M))%mod
        else:
            ans2 = ans2*(heapq.heappop(P)*heapq.heappop(P))%mod
    elif len(P)==0:
        if len(M)>=2:
            ans2 = ans2*(heapq.heappop(M)*heapq.heappop(M))%mod
            i += 1
        else:
            ans2 = ans2*heapq.heappop(M)%mod
    elif len(M)==0:
        ans2 = -ans2*heapq.heappop(P)%mod
    elif len(M)==1 and len(P)==1:
        ans2 = -ans2*heapq.heappop(P)%mod
    elif len(P)==1:
        if(P[0]<M[0]*M[1]):
            ans2 = ans2*(heapq.heappop(M)*heapq.heappop(M))%mod
            i +=1
        else:
            ans2 = -ans2*heapq.heappop(P)%mod
    elif len(M)==1:
        ans2 = -ans2*heapq.heappop(P)%mod

print(ans2)