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:
from bisect import bisect_left
N,K=map(int, input().split())
A=list(map(int, input().split()))
p=10**9+7
A=sorted(A)
thresh=bisect_left(A,0)
minus=A[:thresh]
plus=A[thresh:][::-1]

#print(plus, minus)
if len(plus)==0:
    ans=1
    if K%2!=0:
        minus=minus[::-1]
        for i in range(K):
            ans*=minus[i]
            ans%=p
    else:
        for i in range(K):
            ans*=minus[i]
            ans%=p
    print(ans)
    exit()

if len(minus)==0:
    ans=1
    for i in range(K):
        ans*=plus[i]
        ans%=p
    print(ans)
    exit()

midx=0
pidx=0
ans=1

while K>0 and (0<=midx<len(minus) or 0<=pidx<len(plus)):
    if midx==len(minus)-1:
        nexmin=minus[midx]
    elif midx>=len(minus):
        nexmin=-1
    else:
        nexmin=minus[midx]*minus[midx+1]

    if pidx==len(plus)-1:
        nexplus=plus[pidx]
        fact=nexplus
    elif pidx>=len(plus):
        nexplus=-float("INF")
        fact=nexplus
    else:
        #if plus[pidx+1]!=0:
        #    nexplus=plus[pidx]*plus[pidx+1]
        #else:
        #    nexplus=plus[pidx]
        nexplus=plus[pidx]*plus[pidx+1]
        fact=plus[pidx]

    if nexmin>=nexplus and K>=2:
        ans*=nexmin
        ans%=p
        midx+=2
        K-=2
    else:
        ans*=fact
        ans%=p
        pidx+=1
        K-=1


print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
mod = 10**9 + 7
nums = []
p_cnt = 0
for i in list(map(int, input().split())):
    if i >= 0:
        nums.append((i, True))
        p_cnt += 1
    else:
        nums.append((-i, False))
nums.sort()
if p_cnt == 0 and K%2!=0:
    ans = 1
    for k in range(K):
        ans *= -nums[k][0]
        ans %= mod
    print(ans)
    import sys
    sys.exit()
pl = []
ml = []
for k in range(K):
    x, b = nums.pop()
    if b:
        pl.append(x)
    else:
        ml.append(x)
if len(ml) % 2 != 0:
    while nums:
        x, b = nums.pop()
        if b:
            if ml:
                ml.pop()
                pl.append(x)
                break
        else:
            if pl:
                pl.pop()
                ml.append(x)
                break
ans = 1
for x in pl:
    ans *= x
    ans %= mod
for x in ml:
    ans *= x
    ans %= mod
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
mod = 10**9 + 7
nums = []
p_cnt = 0
for i in list(map(int, input().split())):
    if i >= 0:
        nums.append((i, True))
        p_cnt += 1
    else:
        nums.append((-i, False))
nums.sort()
if p_cnt == 0 and K%2!=0:
    ans = 1
    for k in range(K):
        ans *= -nums[k][0]
        ans %= mod
        print(ans)
    print(ans)
    import sys
    sys.exit()
pl = []
ml = []
for k in range(K):
    x, b = nums.pop()
    if b:
        pl.append(x)
    else:
        ml.append(x)
if len(ml) % 2 != 0:
    while nums:
        x, b = nums.pop()
        if b:
            if ml:
                ml.pop()
                pl.append(x)
                break
        else:
            if pl:
                pl.pop()
                ml.append(x)
                break
ans = 1
for x in pl:
    ans *= x
    ans %= mod
for x in ml:
    ans *= x
    ans %= mod
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = []
c = []
d = 1
m = 10**9+7
for i in range(n):
    if a[i] < 0:
        c.append(a[i])
    else:
        b.append(a[i])
b.sort()
c.sort(reverse=True)
if len(b) == 0:
    for i in range(k):
        d = d*a[i]%m
else:
    while k > 0:
        if len(b) > 1 and len(c) > 1:
            if b[-1]*b[-2] < c[-1]*c[-2] and k > 1:
                d = d*c.pop()%m
                d = d*c.pop()%m
                k -= 2
            else:
                d = d*b.pop()%m
                k -= 1
        elif len(b) == 1 and len(c) > 1:
            if k > 1:
                d = d*c.pop()%m
                d = d*c.pop()%m
                k -= 2
            else:
                d = d*b.pop()%m
                k -= 1
        elif len(b) >= 1 and len(c) <= 1:
            d = d*b.pop()%m
            k -= 1
        else:
            d = d*c.pop()%m
            k -= 1
print(d)

Submission status: Wrong Answer

Solution code:
mod = 10**9+7

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

p = 1
m = 0
ans=1
cnt = 0

while cnt < K-1:
  if A[m]*A[m+1] > A[-p]*A[-p-1]:
    ans = ans*A[m]*A[m+1]%mod
    m +=2
    cnt +=2
    
  else:
    ans = ans*A[-m]%mod
    p +=1
    cnt +=1

if cnt == K-1:
  ans = ans*A[-p]%mod
  
if A[-1] < 0 and K%2==1:
  ans=1
  for i in A[N-K:]:
    ans = ans*i%mod
    
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
mod = 10**9 + 7
nums = []
p_cnt = 0
for i in list(map(int, input().split())):
    if i >= 0:
        nums.append((i, True))
        p_cnt += 1
    else:
        nums.append((-i, False))
nums.sort()
if p_cnt == 0:
    ans = 1
    for k in range(K):
        ans *= -nums[-k-1][0]
        ans %= mod
    print(ans)
    import sys
    sys.exit()
pl = []
ml = []
for k in range(K):
    x, b = nums.pop()
    if b:
        pl.append(x)
    else:
        ml.append(x)
if len(ml) % 2 != 0:
    while nums:
        x, b = nums.pop()
        if b:
            if ml:
                ml.pop()
                pl.append(x)
                break
        else:
            if pl:
                pl.pop()
                ml.append(x)
                break
ans = 1
for x in pl:
    ans *= x
    ans %= mod
for x in ml:
    ans *= x
    ans %= mod
print(ans)

Submission status: Wrong Answer

Solution code:
mod = 10**9+7

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

p = 1
m = 0
ans=1
cnt = 0

while cnt < K-1:
  if A[m]*A[m+1] > A[-p]*A[-p-1]:
    ans *= (A[m]*A[m+1]%mod)
    m +=2
    cnt +=2
    
  else:
    ans *= (A[-m]%mod)
    p +=1
    cnt +=1

if cnt == K-1:
  ans *= (A[-p]%mod)
  
if A[-1] < 0 and K%2==1:
  ans=1
  for i in A[N-K:]:
    ans *= (i%mod)
    
print(ans)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left,bisect_right
mod = 10**9+7

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

p = 1
m = 0
ans=1
cnt = 0

while cnt < K-1:
  if A[m]*A[m+1] > A[-p]*A[-p-1]:
    ans *= A[m]*A[m+1]%mod
    m +=2
    cnt +=2
    
  else:
    ans *= A[-m]%mod
    p +=1
    cnt +=1

if cnt == K-1:
  ans *= A[-p]%mod
  
if A[-1] < 0 and K%2==1:
  ans=1
  for i in A[N-K:]:
    ans *= i%mod
    
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, k = LI()
a = LI()
a.sort(key = lambda x:abs(x), reverse = True)
ans = 1
p = 0
m = 0
plus = []
minus = []
f = 0
for i in range(k):
    if a[i] >= 0:
        plus.append(a[i])
        p += 1
        ans *= a[i]
        ans %= mod
    else:
        minus.append(a[i])
        m += 1
        f ^= 1
        ans *= -a[i]
        ans %= mod
if f:
    ans = -ans
if ans < 0:
    if k == n:
        print(ans)
    elif p == 0:
        a.sort(key = lambda x:abs(x))
        ans = 1
        for i in range(k):
            ans *= -a[i]
            ans %= mod
        if k % 2:
            ans = -ans
        print(ans % mod)
    else:
        ans1 = ans // minus[-1]
        f1 = 0
        f2 = 0
        for i in range(k, n):
            if a[i] >= 0:
                ans1 *= a[i]
                f1 = 1
                break
        ans2 = ans // plus[-1]
        ans2 = -ans2
        for i in range(k, n):
            if a[i] < 0:
                ans2 *= -a[i]
                f2 = 1
                break
        if f1 and f2:
            print(max(ans1, ans2) % mod)
        elif f1:
            print(ans1 % mod)
        else:
            print(ans2 % mod)
else:
    print(ans)

Submission status: Wrong Answer

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

N, K = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
p = 10 ** 9 + 7
A.sort(key = lambda x : abs(x)) # 絶対値小→大
A_zpos = [a for a in A if a >= 0]
A_neg = [a for a in A if a < 0]

ans = 1
k = K
while k > 0:
    if k == 1:
        if A_zpos:
            ans *= A_zpos.pop()
            k -= 1
        else:
            ans = 1
            for i in range(K):
                ans = ans * A[i] % p
            break
    else:
        if len(A_zpos) == len(A_neg) == 1:
            ans = ans * A_zpos.pop() * A_neg.pop() % p
            k -= 2
        elif k % 2 == 1 and len(A_zpos) == 2 and len(A_neg) >= 2:
            ans = ans * A_neg.pop() * A_neg.pop() % p
            k -= 2
        else:
            next_zpos = -1 if len(A_zpos) < 2 else A_zpos[-1] * A_zpos[-2] % p
            next_neg = -1 if len(A_neg) < 2 else A_neg[-1] * A_neg[-2] % p
            if next_zpos >= next_neg:
                ans = ans * A_zpos.pop() * A_zpos.pop() % p
            else:
                ans = ans * A_neg.pop() * A_neg.pop() % p
            k -= 2

print(ans)

Submission status: Wrong Answer

Solution code:
mod = 10**9+7

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

p = 1
m = 0
ans=1
cnt = 0

while cnt < K-1:
  if A[m]*A[m+1] > A[-p]*A[-p-1]:
    ans *= A[m]*A[m+1]%mod
    m +=2
    cnt +=2
    
  else:
    ans *= A[-m]%mod
    p +=1
    cnt +=1

if cnt == K-1:
  ans *= A[-p]%mod
  
if A[-1] < 0 and K%2==1:
  ans=1
  for i in A[N-K:]:
    ans *= i%mod
    
print(ans)

Submission status: Wrong Answer

Solution code:
#! /usr/bin/env python3

import sys
import numpy as np
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)
MOD = pow(10, 9) + 7

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

if K == N:
    ans = 1
    for a in A:
        ans *= a
        ans %= MOD
    print(ans)
    sys.exit()

A_pos = [a for a in A if a >= 0]
A_neg = [a for a in A if a < 0]

if len(A_pos) == 0:
    if K % 2 == 1:
        A = sorted(A, key=lambda x: abs(x))
    else:
        A = sorted(A, key=lambda x: -abs(x))
    ans = 1
    for a in A_neg[:K]:
        ans *= a
        ans %= MOD
    print(ans)
    sys.exit()

A_pos = sorted(A_pos, key=lambda x: -abs(x))
A_neg = sorted(A_neg, key=lambda x: -abs(x))
ans = 1
r = K
if r % 2 == 1:
    ans *= A_pos[0]
    ans %= MOD
    A_pos = A_pos[1:]
    r -= 1

while r > 0:
    if len(A_pos) <= 1:
        ans *= A_neg[0] * A_neg[1]
        ans %= MOD
    elif len(A_neg) <= 1:
        ans *= A_pos[0] * A_pos[1]
        ans %= MOD
    else:
        acc_pos = A_pos[0] * A_pos[1]
        acc_neg = A_neg[0] * A_neg[1]

        if acc_pos > acc_neg:
            ans *= acc_pos
            ans %= MOD
        else:
            ans *= acc_neg
            ans %= MOD
    r -= 2
print(ans % MOD)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, k = LI()
a = LI()
a.sort(key = lambda x:abs(x), reverse = True)
ans = 1
p = 0
m = 0
plus = []
minus = []
f = 0
for i in range(k):
    if a[i] >= 0:
        plus.append(a[i])
        p += 1
        ans *= a[i]
        ans %= mod
    else:
        minus.append(a[i])
        m += 1
        f ^= 1
        ans *= -a[i]
        ans %= mod
if f:
    ans = -ans
if ans < 0:
    if k == n:
        print(ans)
    elif p == 0:
        a.sort(key = lambda x:abs(x))
        ans = 1
        for i in range(k):
            ans *= -a[i]
            ans %= mod
        if k % 2:
            ans = -ans
        print(ans % mod)
    else:
        ans1 = ans // minus[-1]
        ans2 = -inf
        for i in range(k, n):
            if a[i] >= 0:
                ans1 *= a[i]
                break
        ans2 = ans // plus[-1]
        ans2 = -ans2
        for i in range(k, n):
            if a[i] < 0:
                ans2 *= -a[i]
        print(max(ans1, ans2) % mod)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = []
c = []
d = 1
m = 10**9+7
for i in range(n):
    if a[i] < 0:
        c.append(a[i])
    else:
        b.append(a[i])
b.sort()
c.sort(reverse=True)
if len(b) == 0:
    for i in range(k):
        d = d*a[i]%m
else:
    while k > 0:
        if len(b) > 1 and len(c) > 1:
            if b[-1]*b[-2] < c[-1]*c[-2]:
                d = d*c.pop()%m
                d = d*c.pop()%m
                k -= 2
            else:
                d = d*b.pop()%m
                k -= 1
        elif len(b) == 1 and len(c) > 1:
            if k > 1:
                d = d*c.pop()%m
                d = d*c.pop()%m
                k -= 2
                
            else:
                d = d*b.pop()%m
                k -= 1
        elif len(b) >= 1 and len(c) <= 1:
            d = d*b.pop()%m
            k -= 1
        else:
            d = d*c.pop()%m
            k -= 1
print(d)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#
# Author: Tetsuya Ishikawa <tiskw111@gmail.com>
# Date  : July 05, 2020
##################################################### SOURCE START #####################################################

import heapq
import collections

class HeapQueue:

    def __init__(self, xs, mode):
        if   mode == "min": self.xs = [+x for x in xs]
        elif mode == "max": self.xs = [-x for x in xs]
        else              : raise NotImplementedError("HeapQueue.__init__: mode should be 'min' or 'max'")
        heapq.heapify(xs)
        self.mode = mode

    def __len__(self):
        return len(self.xs)

    def pop(self):
        if   self.mode == "min": return heapq.heappop(self.xs)
        elif self.mode == "max": return heapq.heappop(self.xs) * (-1)

    def push(self, x):
        if   self.mode == "min": return heapq.heappush(self.xs,  x)
        elif self.mode == "max": return heapq.heappush(self.xs, -x)

    # @staticmethod
    # def __test01__():
    #     xs = HeapQueue([-3, 2, 9, -4], "min")
    #     x0 = xs.pop()
    #     x1 = xs.pop()
    #     x2 = xs.pop()
    #     x3 = xs.pop()
    #     return (x0 == -4 and x1 == -3 and x2 == 2 and x3 == 9)


N, K = tuple(map(int, input().strip().split()))
As = list(map(int, input().strip().split()))

D = int(1E9 + 7)
r = 1

if N == K:

    for a in As:
        r = (r * a) % D

elif all(a >= 0 for a in As):

    As = sorted(As, reverse=True)
    for a in As[:K]:
        r = (r * a) % D

elif K % 2 == 1 and all(a < 0 for a in As):

    As = sorted(As, reverse=True)
    for a in As[:K]:
        r = (r * a) % D

elif K % 2 == 0 and all(a < 0 for a in As):

    As = sorted(As)
    for a in As[:K]:
        r = (r * a) % D

else:

    As = sorted(As, key = lambda a: abs(a), reverse=True)

    used = As[:K]
    rest = As[K:]
    num_negative_sign = sum([1 if x < 0 else 0 for x in used])

    if num_negative_sign % 2 != 0:

        used_min_pos = None
        used_min_neg = None
        for k in range(K-1, -1, -1):
            if   used_min_pos is None and used[k] >= 0: used_min_pos = k
            elif used_min_neg is None and used[k] <  0: used_min_neg = k
            if used_min_pos and used_min_neg:
                break

        rest_min_pos = None
        rest_min_neg = None
        for k in range(N-K):
            if   rest_min_pos is None and rest[k] >= 0: rest_min_pos = k
            elif rest_min_neg is None and rest[k] <  0: rest_min_neg = k
            if rest_min_pos and rest_min_neg:
                break

        # print(used_min_pos)
        # print(used_min_neg)
        # print(rest_min_pos)
        # print(rest_min_neg)

        if used_min_pos is None or rest_min_neg is None:
            used[used_min_neg] = rest[rest_min_pos]
        elif used_min_neg is None or rest_min_pos is None:
            used[used_min_pos] = rest[rest_min_neg]
        else:
            v1 = abs(used[used_min_pos] * rest[rest_min_neg])
            v2 = abs(used[used_min_neg] * rest[rest_min_pos])
            if v1 < v2:
                used[used_min_pos] = rest[rest_min_neg]
            else:
                used[used_min_neg] = rest[rest_min_pos]

    for a in used:
        r = (r * a) % D

print(r)

##################################################### SOURCE FINISH ####################################################
# vim: expandtab tabstop=4 shiftwidth=4 fdm=marker

Submission status: Wrong Answer

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

list.sort(a, reverse=True)
total = 1
count_a = 0
count_b = N-1


if a[0]<0 and K%2 != 0:
	for i in range(N):
		a[i] = abs(a[i])
	list.sort(a, reverse=False)
	for i in range(K):
		total *= a[i]
		total  =total%(10**9 +7)
	total *= -1
	total  =total%(10**9 +7)
else:
	while K>0:

		if K %2 == 1:
			total *= max( a[count_a], a[count_b])
			K -= 1
			count_a += 1
		if K> 1:
			if a[count_a]*a[count_a+1] >a[count_b]*a[count_b-1]:
				total *= a[count_a] * a[count_a+1]
				total  =total%(10**9 +7)
				count_a += 2
			else:
				total *= a[count_b]*a[count_b-1]
				count_b -= 2
				total  =total%(10**9 +7)
			K-=2
		else:
			total *= max( a[count_a], a[count_b])
			total  =total%(10**9 +7)
		K -= 1
print(total)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
A.sort()
mod=10**9+7

def design(A,k):
    l=0
    r=len(A)-1
    ans=1
    while k>0:
        lv=A[0]*A[1]
        rv=A[r]*A[r-1]
        if lv>rv:
            ans*=lv
            l+=2
        else:
            ans*=rv
            r-=2
        ans%=mod
        k-=2
    return ans

ans=1
if A[-1]==0:
    ans=0
elif K%2==1:
    if A[-1]>0:
        ans=A[-1]*design(A[:-1],K-1)
    else:
        ans=A[-1]
        for i in range(1,K):
            ans*=A[-1-i]
            ans%=mod
else:
    ans*=design(A,K)

print(ans%mod)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
*A, = map(int, input().split())
p = 10**9 + 7
A.sort()
ans = 1
i = 0
j = n - 1
if k % 2 == 1:
    ans *= A[j]
    ans %= p
    j -= 1
    k -= 1
for _ in range(k // 2):
    left = A[i] * A[i + 1]
    right = A[j] * A[j - 1]
    if (left > right):
        ans *= left
        ans %= p
        i += 2
    else:
        ans *= right
        ans %= p
        j -= 2
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
mod = 10**9 + 7
nums = []
p_cnt = 0
for i in list(map(int, input().split())):
    if i >= 0:
        nums.append((i, True))
        p_cnt += 1
    else:
        nums.append((-i, False))
nums.sort()
if p_cnt == 0:
    ans = 1
    for k in range(K):
        ans *= -nums[k][0]
        ans %= mod
    print(ans)
    import sys
    sys.exit()
pl = []
ml = []
for k in range(K):
    x, b = nums.pop()
    if b:
        pl.append(x)
    else:
        ml.append(x)
if len(ml) % 2 != 0:
    while nums:
        x, b = nums.pop()
        if b:
            if ml:
                ml.pop()
                pl.append(x)
                break
        else:
            if pl:
                pl.pop()
                ml.append(x)
                break
ans = 1
for x in pl:
    ans *= x
    ans %= mod
for x in ml:
    ans *= x
    ans %= mod
print(ans)

Submission status: Wrong Answer

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

list.sort(a, reverse=True)
total = 1
count_a = 0
count_b = N-1


if a[0]<0 and K%2 != 0:
	for i in range(N):
		a[i] = abs(a[i])
	list.sort(a, reverse=False)
	for i in range(K):
		total *= a[i]
		total  =total%(10**9 +7)
	total *= -1
	total  =total%(10**9 +7)
else:
	while K>0:

		if K %2 == 1:
			total += max( a[count_a], a[count_b])
			K -= 1
			count_a += 1
		if K> 1:
			if a[count_a]*a[count_a+1] >a[count_b]*a[count_b-1]:
				total *= a[count_a] * a[count_a+1]
				total  =total%(10**9 +7)
				count_a += 2
			else:
				total *= a[count_b]*a[count_b-1]
				count_b -= 2
				total  =total%(10**9 +7)
			K-=2
		else:
			total *= max( a[count_a], a[count_b])
			total  =total%(10**9 +7)
		K -= 1
print(total)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
m=10**9+7
ans=0
if n==k:
  ans=a[0]
  for i in range(1,n):
    ans=(ans*a[i])%m
else:
  a.sort()
  if a[n-1]<0:
    ans=a[n-1]
    for i in range(n-2,n-k-1,-1):
      ans=(ans*a[i])%m
  else:
    if k&1:
      ans=a[n-1]
      plus=n-2
      pluss=a[n-2]*a[n-3]
    else:
      ans=1
      plus=n-1
      pluss=a[n-1]*a[n-2]
    minus=0
    minuss=a[0]*a[1]
    for i in range(k//2):
      if minuss>=pluss:
        ans=(ans*(minuss%m))%m
        minus+=2
        minuss=a[minus]*a[minus+1]
      else:
        ans=(ans*(plus%m))%m
        plus-=2
        pluss=a[plus]*a[plus-1]
print(ans)

Submission status: Wrong Answer

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

list.sort(a, reverse=True)
total = 1
count_a = 0
count_b = N-1


if a[0]<0 and K%2 != 0:
	for i in range(N):
		a[i] = abs(a[i])
	list.sort(a, reverse=False)
	for i in range(K):
		total *= a[i]
		total  =total%(10**9 +7)
	total *= -1
	total  =total%(10**9 +7)
else:
	while K>0:

		if K %2 == 1:
			total += max( a[count_a], a[count_b])
			K -= 1
		if K> 1:
			if a[count_a]*a[count_a+1] >a[count_b]*a[count_b-1]:
				total *= a[count_a] * a[count_a+1]
				total  =total%(10**9 +7)
				count_a += 2
			else:
				total *= a[count_b]*a[count_b-1]
				count_b -= 2
				total  =total%(10**9 +7)
			K-=2
		else:
			total *= max( a[count_a], a[count_b])
			total  =total%(10**9 +7)
		K -= 1
print(total)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
#
# Author: Tetsuya Ishikawa <tiskw111@gmail.com>
# Date  : July 05, 2020
##################################################### SOURCE START #####################################################

import heapq
import collections

class HeapQueue:

    def __init__(self, xs, mode):
        if   mode == "min": self.xs = [+x for x in xs]
        elif mode == "max": self.xs = [-x for x in xs]
        else              : raise NotImplementedError("HeapQueue.__init__: mode should be 'min' or 'max'")
        heapq.heapify(xs)
        self.mode = mode

    def __len__(self):
        return len(self.xs)

    def pop(self):
        if   self.mode == "min": return heapq.heappop(self.xs)
        elif self.mode == "max": return heapq.heappop(self.xs) * (-1)

    def push(self, x):
        if   self.mode == "min": return heapq.heappush(self.xs,  x)
        elif self.mode == "max": return heapq.heappush(self.xs, -x)

    # @staticmethod
    # def __test01__():
    #     xs = HeapQueue([-3, 2, 9, -4], "min")
    #     x0 = xs.pop()
    #     x1 = xs.pop()
    #     x2 = xs.pop()
    #     x3 = xs.pop()
    #     return (x0 == -4 and x1 == -3 and x2 == 2 and x3 == 9)


N, K = tuple(map(int, input().strip().split()))
As = list(map(int, input().strip().split()))

D = int(1E9 + 7)
r = 1

if N == K:

    for a in As:
        r = (r * a) % D

elif all(a >= 0 for a in As):

    As = sorted(As, reverse=True)
    for a in As[:K]:
        r = (r * a) % D

elif K % 2 == 1 and all(a < 0 for a in As):

    As = sorted(As, reverse=True)
    for a in As[:K]:
        r = (r * a) % D

elif K % 2 == 0 and all(a < 0 for a in As):

    As = sorted(As)
    for a in As[:K]:
        r = (r * a) % D

else:

    As = sorted(As, key = lambda a: abs(a), reverse=True)

    used = As[:K]
    rest = As[K:]
    num_negative_sign = sum([1 if x < 0 else 0 for x in used])

    if num_negative_sign % 2 != 0:

        used_min_pos = None
        used_min_neg = None
        for k in range(K-1, -1, -1):
            if   used_min_pos is None and used[k] >= 0: used_min_pos = k
            elif used_min_neg is None and used[k] <  0: used_min_neg = k
            if used_min_pos and used_min_neg:
                break

        rest_min_pos = None
        rest_min_neg = None
        for k in range(N-K-1, -1, -1):
            if   rest_min_pos is None and rest[k] >= 0: rest_min_pos = k
            elif rest_min_neg is None and rest[k] <  0: rest_min_neg = k
            if rest_min_pos and rest_min_neg:
                break

        if used_min_pos is None or rest_min_neg is None:
            used[used_min_neg] = rest[rest_min_pos]
        elif used_min_neg is None or rest_min_pos is None:
            used[used_min_pos] = rest[rest_min_neg]
        else:
            v1 = abs(used[used_min_pos] * rest[rest_min_neg])
            v2 = abs(used[used_min_neg] * rest[rest_min_pos])
            if v1 < v2:
                used[used_min_pos] = rest_min_neg
            else:
                used[used_min_neg] = rest_min_pos


    for a in used:
        r = (r * a) % D

print(r)

##################################################### SOURCE FINISH ####################################################
# vim: expandtab tabstop=4 shiftwidth=4 fdm=marker

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
n,k = map(int,input().split())
a_list = sorted(map(int,input().split()))
mod = 10**9+7
if n-k < a_list.count(0):
    print(0)
    exit()
if (sum([1 for a in a_list if np.sign(a)!=-1])==0 and k%2==1) or (k==n and len([1 for a in a_list if np.sign(a)==-1])%2==1):
    a_list.sort(key = abs)
    ans = 1
    for num in a_list[:k]:
        ans *= num
        ans %= mod
    print(ans)
    exit()
else:
    a_list.sort(key = abs,reverse = True)
    add = 1
    remove = 1
    if len([a for a in a_list[:k] if np.sign(a)==-1])%2!=0:
        negative_big = [num for num in a_list[:k] if np.sign(num)==-1]
        positive_big = [num for num in a_list[:k] if np.sign(num)!=-1]
        negative_small = [num for num in a_list[k:] if np.sign(num)==-1]
        positive_small = [num for num in a_list[k:] if np.sign(num)!=-1]
        
        
        if len(negative_big)==0 or len(positive_small)==0:
            remove = min(positive_big)
            add = min(negative_small)
        elif len(positive_big)==0 or len(negative_small)==0:
            remove = max(negative_big)
            add = max(positive_small)
        else:
            positive_small_max = max(positive_small)
            negative_big_max = max(negative_big)
            negative_small_min = min(negative_small)
            positive_big_min = min(positive_big)
            if positive_small_max/negative_big_max <= negative_small_min/positive_big_min:
                remove = negative_big_max
                add = positive_small_max
            else:
                remove = positive_big_min
                add = negative_small_min
ans = 1
for num in a_list[:k]:
    ans *= num
    ans %= mod
    
if len([a for a in a_list[:k] if np.sign(a)==-1])%2!=0:
    ans *= add
    ans %= mod
    ans *= pow(remove, mod-2, mod)
    ans %= mod

print(ans)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left, bisect_right
from collections import deque

mod = 10 ** 9 + 7
n, k = map(int, input().split())
A = list(map(int, input().split()))
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)
    AP = deque(A_plus)
    A_minus = A[:n_minus]
    AM = deque(A_minus)
    minus_num_max = min(n_minus // 2, k // 2)
    select = k - 2 * minus_num_max  # 選ばざるを得ない数
    if n_plus < select:
        print(0)
        exit()
    kouho = []
    while k > 0:
        kouho1, kouho2, kouho3, kouho4 = 0, 0, 0, 0
        if n_plus >= 2:
            kouho1 = AP.popleft()
            kouho2 = AP.popleft()
            plus_kouho = kouho1 * kouho2
        elif n_plus == 1:
            kouho1 = AP.popleft()
            kouho2 = 0
            plus_kouho = kouho1
        else:
            kouho1, kouho2 = 0, 0
            plus_kouho = 0

        if n_minus >= 2:
            kouho3 = AM.popleft()
            kouho4 = AM.popleft()
            minus_kouho = kouho3 * kouho4
        else:
            kouho3 = 0
            kouho4 = 0
            minus_kouho = -1
        if plus_kouho > minus_kouho:
            n_plus -= 1
            k -= 1
            ans *= kouho1
            if kouho2 > 0:
                AP.appendleft(kouho2)
            ans %= mod
            if minus_kouho > 0:
                AM.appendleft(kouho4)
                AM.appendleft(kouho3)
        else:
            k -= 2
            n_minus -= 2
            ans *= minus_kouho
            ans %= mod
            if plus_kouho > 0:
                if kouho2 > 0:
                    AP.appendleft(kouho2)
                if kouho1 > 0:
                    AP.appendleft(kouho1)


print(ans % mod)