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 = [int(a) for a in input().split()]

mod = 10**9+7

cp = 0
cm = 0
for i in range(N):
    n = 1
    if A[i] < 0:
        n = -1
    elif A[i] == 0:
        n = 0
    A[i] = (abs(A[i]), n)
    if n > 0:
        cp += 1
    elif n < 0:
        cm += 1

f = -1
for i in range(0, K+1, 2):
    if i <= cm and K-i <= cp:
        f = 1
        break


if K > cp+cm:
    ans = 0
elif f == -1:
    A.sort()
    ans = 1
    for i in range(K):
        ans *= A[i][0]
        ans %= mod
    ans *= -1
    ans %= mod
else:
    A.sort(reverse=True)
    cnt = 0
    ans = 1
    for i in range(K):
        ans *= A[i][0]
        ans %= mod
        if A[i][1] < 0:
            cnt += 1

    if cnt % 2 == 1:
        a1 = 1
        if K > cnt and cnt < cm:
            for i in range(K, N):
                if A[i][1] < 0:
                    a1 *= A[i][0]
                    break
            for i in range(K-1, -1, -1):
                if A[i][1] > 0:
                    a1 /= A[i][0]
                    break
        else:
            a1 = -1
        a2 = 1
        if cnt > 0 and cnt < cp:
            for i in range(K, N):
                if A[i][1] > 0:
                    a2 *= A[i][0]
                    break
            for i in range(K-1, -1, -1):
                if A[i][1] < 0:
                    a2 /= A[i][0]
                    break
        else:
            a2 = 0
        if a1 > a2 >= 0:
            for i in range(K, N):
                if A[i][1] < 0:
                    ans *= A[i][0]
                    break
            for i in range(K-1, -1, -1):
                if A[i][1] > 0:
                    ans *= pow(A[i][0], mod-2, mod)
                    ans %= mod
                    break
        elif a2 > a1 >= 0:
            for i in range(K, N):
                if A[i][1] > 0:
                    ans *= A[i][0]
                    break
            for i in range(K-1, -1, -1):
                if A[i][1] < 0:
                    ans *= pow(A[i][0], mod-2, mod)
                    ans %= mod
                    break
        else:
            ans = 0

print(ans)

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 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:
mod = 10**9 + 7
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
index_change = 0
ans = 1
for i in range(n-1):
    if a[i] <= 0 and a[i+1] > 0:
        index_change = i+1
        break
else:
    for i in range(1, k+1):
        ans *= a[-i]
        ans %= mod
    print(ans)
    exit()
l = 0
r = n-1
while k > 0:
    if k == 1:
        if r >= index_change:
            ans *= a[r]
            ans %= mod
            break
        else:
            ans *= a[l]*a[l+1]
            ans %= mod
            ans *= pow(a[r+1], mod-2, mod)
            ans %= mod
            break
    else:
        left = a[l]*a[l+1]
        right = a[r]*a[r-1]
        if left >= right:
            ans *= left
            ans %= mod
            l += 2
        else:
            ans *= right
            ans %= mod
            r -= 2
        k -= 2
print(ans)

Submission status: Wrong Answer

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

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

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

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

    return 0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
N, K = map(int,input().split())
A = list(map(int,input().split()))

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

plus.sort(reverse = True)
minus.sort() #絶対値の大きい順
Lp = len(plus)
Lm = len(minus)
idx_p = 0
idx_m = 0


MOD = 10**9+7

if K>Lp: #必ずマイナス
    A.sort(key = lambda x:abs(x))
    ans = 1
    for i in range(K):
        ans *= A[i]
        ans = (ans + MOD)%MOD
    print(ans)
    sys.exit()


# 2個ずつ見る
Ks = 0
ans = 1
while Ks<K:
    if Ks+1==K:
        if idx_p<Lp:
            ans *= plus[idx_p]
            ans %= MOD
        else:
            ans *= minus[-1]
            ans += MOD
            ans %= MOD
        break
    
    if idx_p<Lp-1 and idx_m<Lm-1:
        if plus[idx_p]*plus[idx_p+1]>minus[idx_m]*minus[idx_m+1]:
            ans *= plus[idx_p] * plus[idx_p+1]
            ans %= MOD
            idx_p += 2
        else:
            ans *= minus[idx_m] * minus[idx_m+1]
            ans %= MOD
            idx_m += 2
        Ks += 2
    elif idx_m<Lm-1:
        ans *= minus[idx_m]*minus[idx_m+1]
        ans %= MOD
        idx_m += 2
        Ks += 2
    elif idx_p<Lp-1:
        ans *= plus[idx_p] * plus[idx_p+1]
        ans %= MOD
        idx_p += 2
        Ks += 2

print((ans+MOD)%MOD)

Submission status: Wrong Answer

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

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

ans = 1
mod = 10 ** 9 + 7

minus_cnt = 0
for a in A:
    if a < 0:
        minus_cnt += 1

if K == 1:
    print(max(A))
elif K == N:
    for a in A:
        ans *= abs(a)
        ans %= mod
    if minus_cnt % 2 == 1:
        ans *= (-1)
    print(ans % mod)
else:
    minus_cnt = 0
    new_A = []
    select_ls = []

    for a in A:
        new_A.append([abs(a), 0 if a >= 0 else -1])
    new_A.sort(reverse=True)

    for i in range(K):
        select_ls.append(new_A[i])
        minus_cnt += new_A[i][1]

    if minus_cnt % 2 == 0:
        for s in select_ls:
            ans *= s[0]
            ans %= mod
        print(ans)
    else:
        ok = False
        for i in range(K, N):
            if new_A[i][1] == 0:
                ok = True
                ans *= new_A[i][0]
                select_ls.sort()
                for j in range(1, len(select_ls)):
                    ans *= select_ls[j][0]
                    ans %= mod
                break
        if not ok:
            if 0 in A:
                print(0)
                exit()
            new_A.sort()
            for i in range(K):
                ans *= new_A[i][0]
                ans %= mod
            ans *= (-1)
        print(ans % mod)

Submission status: Wrong Answer

Solution code:

def inverse(a): #aのmodを法にした逆元を返す
    return pow(a,mod-2,mod)

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

B = []
zero = 0
pl = 0
mi = 0
for i in A:
    if i == 0:
        zero += 1
    else:
        B.append( ( abs(i) , i // abs(i) ) )
        if i < 0:
            mi += 1
        else:
            pl += 1

last_pl = None

B.sort()
B.reverse()
mod = 10**9+7

if N - zero < K:
    print (0)
    sys.exit()

if pl == 0:

    if K % 2 == 0:
        now = 1
        for i in range(K):
            now *= B[i][0]
            now %= mod
        print (now % mod)
        sys.exit()
    else:
        now = 1
        if zero > 0:
            print (0)
            sys.exit()
        
        for i in range(K):
            now *= B[N-i-1][0] * B[N-i-1][1]
            now %= mod
        print (now % mod)
        sys.exit()


lasp = None
lasm = None

now = 1
for i in range(K):
    now *= B[i][0] * B[i][1]

    if now >= 0:
        now %= mod
    else:
        now = now % mod - mod

    if B[i][1] > 0:
        lasp = B[i][0]
    else:
        lasm = -1 * B[i][0]

print (lasp,lasm)
if now > 0:
    print (now % mod)
    sys.exit()

else:

    if lasp == None:
        change2 = float("-inf")
        a2 = 0
    else:
        a2 = now * inverse(lasp)
        change2 = 1 / lasp
        for i in range(K+1,len(B)):
            if B[i][1] < 0:
                a2 *= -1 * B[i][0]
                change2 *= B[i][0]
                break
        else:
            change2 = float("-inf")

    if lasm == None:
        change3 = float("-inf")
        a3 = 0
    else:
    
        a3 = now * inverse(lasm % mod)
        change3 = 1 / lasm
        for i in range(K+1,len(B)):
            if B[i][1] > 0:
                a3 *= B[i][0]
                change3 *= B[i][0]
                break
        else:
            change3 = float("-inf")

    #print (a2,a3)
    if change2 > change3:
        print (a2 % mod)
    else:
        print (a3 % mod)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
from bisect import bisect_right


def solve(*args: str) -> str:
    n, k = map(int, args[0].split())
    A = sorted(map(int, args[1].split()))
    mod = 10**9+7

    neg = 0

    cnt = 0
    ret = 1

    n_pos = n-bisect_right(A, 0)
    if k <= n_pos or 1 != (k-n_pos) % 2:
        for a in sorted(A, key=lambda x: abs(x), reverse=True):
            if a < 0:
                if neg < 0 and 2 <= k-cnt:
                    neg = (a*neg) % mod
                    ret = (ret*neg) % mod
                    cnt += 2
                    neg = 0
                elif neg == 0:
                    neg = a
            elif 0 < a:
                ret = (ret*a) % mod
                cnt += 1

            if k <= cnt:
                break
    else:
        for a in sorted(A, key=lambda x: abs(x)):
            if a != 0:
                ret = (a*ret) % mod
                cnt += 1
            if k <= cnt:
                break

    if cnt < k:
        ret = 0

    return str(ret)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Submission status: Wrong Answer

Solution code:
from collections import Counter, deque

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

MOD = 10 ** 9 + 7

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

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


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

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

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

    is_minus = False
    if len(minus) % 2 == 1:
        p = None
        m = None
        for i in range(K, N):
            if A[i] >= 0 and p is None:
                p = A[i]
            if A[i] < 0 and m is None:
                m = A[i]
            if p is not None and m is not None:
                break
        if m is None and p is None:
            pass
        elif len(plus) == 0:
            is_minus = True

            # def f(x):
            #     if x == 0:
            #         return 10 ** 9
            #     else:
            #         return abs(x)

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

            # print(ans)
            print(0)
        elif m is None and p is not None:
            minus.pop()
            plus.append(p)
        elif m is not None and p is None:
            plus.pop()
            minus.append(m)
        elif minus[-1] * m > plus[-1] * p:
            plus.pop()
            minus.append(m)
        else:
            minus.pop()
            plus.append(p)

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

    if not is_minus:
        print(ans)

Submission status: Wrong Answer

Solution code:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
import sys
MOD = 10**9 + 7
def main(N, K, A):
    negative = sorted([a for a in A if a < 0])
    neg = len(negative)
    zero = [a for a in A if a == 0]
    positive = sorted([a for a in A if a > 0])
    pos = len(positive)

    if N - K < len(zero):
        return 0
    N -= len(zero)
    A = sorted([a for a in A if a != 0], key=lambda x: abs(x))

    ans = Mint(1)
    if ((neg & (~1)) + pos < K) or (neg & 1 and K == N) or (pos == 0 and K & 1):
        # マイナスになっちゃう
        for i in range(K):
            ans *= abs(A[i])
        ans = -ans
    else:
        # プラスにできる
        A.reverse()
        neg_cnt = 0
        last_pos = 0
        last_cnt = 0
        for i in range(K):
            ans *= abs(A[i])
            if A[i] < 0: neg_cnt += 1
            if neg_cnt & 1 == 0:
                last_pos = ans.value
                last_cnt = i + 1
        remain = K - last_cnt
        if remain == 1:
            for i in range(last_cnt, N):
                if A[i] > 0:
                    ans = Mint(last_pos * A[i])
                    break
        elif remain != 0:
            pospos = 1
            negneg = 1
            pos_rem = remain
            neg_rem = remain
            for i in range(last_cnt, N):
                if A[i] > 0 and pos_rem > 0:
                    pospos *= A[i]
                    pos_rem -= 1
                if A[i] < 0 and neg_rem > 0:
                    negneg *= abs(A[i])
                    neg_rem -= 1
                if pos_rem == neg_rem == 0:
                    break
            pospos = pospos if pos_rem == 0 else 1
            negneg = negneg if neg_rem == 0 else 1
            ans = Mint(last_pos * max(pospos, negneg))

    return ans

class Mint:
    def __init__(self, value=0):
        self.value = value % MOD
        if self.value < 0: self.value += MOD

    @staticmethod
    def get_value(x): return x.value if isinstance(x, Mint) else x

    def inverse(self):
        a, b = self.value, MOD
        u, v = 1, 0
        while b:
            t = a // b
            b, a = a - t * b, b
            v, u = u - t * v, v
        if u < 0: u += MOD
        return u

    def __repr__(self): return str(self.value)
    def __eq__(self, other): return self.value == other.value
    def __neg__(self): return Mint(-self.value)
    def __hash__(self): return hash(self.value)
    def __bool__(self): return self.value != 0

    def __iadd__(self, other):
        self.value = (self.value + Mint.get_value(other)) % MOD
        return self

    def __add__(self, other):
        new_obj = Mint(self.value)
        new_obj += other
        return new_obj
    __radd__ = __add__

    def __isub__(self, other):
        self.value = (self.value - Mint.get_value(other)) % MOD
        if self.value < 0: self.value += MOD
        return self

    def __sub__(self, other):
        new_obj = Mint(self.value)
        new_obj -= other
        return new_obj

    def __rsub__(self, other):
        new_obj = Mint(Mint.get_value(other))
        new_obj -= self
        return new_obj

    def __imul__(self, other):
        self.value = self.value * Mint.get_value(other) % MOD
        return self

    def __mul__(self, other):
        new_obj = Mint(self.value)
        new_obj *= other
        return new_obj
    __rmul__ = __mul__

    def __ifloordiv__(self, other):
        other = other if isinstance(other, Mint) else Mint(other)
        self *= other.inverse()
        return self

    def __floordiv__(self, other):
        new_obj = Mint(self.value)
        new_obj //= other
        return new_obj

    def __rfloordiv__(self, other):
        new_obj = Mint(Mint.get_value(other))
        new_obj //= self
        return new_obj

if __name__ == '__main__':
    input = sys.stdin.readline
    N, K = map(int, input().split())
    *A, = map(int, input().split())
    print(main(N, K, A))

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


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:
# Template 1.0
import sys, re
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx):   return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
    temp = sorted(passedDic.items(), key=lambda kv: (kv[1], kv[0]))
    toret = {}
    for tup in temp:
        toret[tup[0]] = tup[1]
    return toret
def sortDictWithKey(passedDic):
    return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

n, k = MAP()

a = LIST()

pos = []
neg = []
zero = []

for el in a:
    if(el<0):
        neg.append(el)
    elif(el>0):
        pos.append(el)
    else:
        zero.append(el)

pos = sorted(pos)[::-1]
neg = sorted(neg)[::-1]

ans = 1

if(k==n):
    for el in a:
        ans = (ans%mod*el%mod)%mod
else:

    if(len(pos)==0):
        if(k%2==0):
            temp = 0
            for i in range(len(neg)-1, -1, -1):
                if(temp==k):
                    break
                ans = (ans%mod*neg[i]%mod)%mod
                temp+=1
            if(temp<k):
                ans = 0
        else:
            temp = 0
            for i in range(len(neg) - 1):
                if (temp == k):
                    break
                ans = (ans%mod * neg[i]%mod) % mod
                temp += 1
            if (temp < k):
                ans = 0
    else:

        left = k

        i,j = 0, len(neg)-1

        while(left>1):
            temp, temp1 = 0, 0
            if(i<len(pos)-2):
                temp = pos[i]*pos[i+1]
                # i+=2
            if(j>=1):
                temp1 = neg[j]*neg[j-1]
                # j-=2
            if(temp==0 and temp1==0):
                break
            if(temp1>temp):
                ans = (ans*(temp1%mod))%mod
                j-=2
            else:
                ans = (ans*(temp%mod))%mod
                i+=2
            left -= 2

        if(left>1):
            ans = 0
        elif(left==1):
            ans = ((ans%mod)*pos[i])%mod
        if(k%2!=0):
            ans1 = 1
            if(i-2>=0 and j-2>=0 and i-2<=len(pos)-1 and j-2<=len(neg)-1):
                for b in range(i-1):
                    ans1 = (ans1%mod*(pos[b]))%mod
                for c in range(len(neg)-1, j-2,-1):
                    ans1 = (ans1%mod*neg[c])%mod
            # print(ans, ans1)
            ans = max(ans, ans1)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int,input().split())
A = list(map(int,input().split()))
lc = []
mod2 = 10**9+7
tmp = -1
m = 0

for i in A:
    if i == 0:
        pp = 0
    if i < 0:
        i *= -1
        lc.append([i,1])
        m += 1
    else:
        lc.append([i,0])
lc.sort(key=lambda x: x[0], reverse=True)
#print(lc)

ans = 1
cnt = 0
pl = []
if m == N and K%2 == 1:
    for i in range(K):
        ans *= -lc[N-i-1][0]
        ans %= mod2
    print(ans)
elif(N == K or m==N):
    for i in range(K):
        ans *= lc[i][0]
        ans %= mod2
        cnt += lc[i][1]
    if cnt%2 == 1:
        ans = -ans
    print(ans)
else:
    for i in range(N):
        if i < K-1:
            cnt += lc[i][1]
            if lc[i][1] == 1:
                tmp = i
        if(i >= K-1):
            if((cnt + lc[i][1])%2 == 0):
                if i == K-1:
                    tmp = -1
                for x in range(i+1):
                    if x != tmp:
                        ans *= lc[x][0]
                        ans %= mod2
                print(ans)
                break
            else:
                if(lc[i][1] == 0 and i >= K):
                    for x in range(i+1):
                        if x != tmp:
                            ans *= lc[x][0]
                            ans %= mod2
                    print(ans)
                    break

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

N,K = map(int,S().split())
A = LI()
mod = 10**9+7

if N == 2 and K == 1:
    M = max(A)
    print(M % mod)
    exit()

a = 0  # 0の個数
b = 0
c = 0
B = []
C = []
D = []
for i in range(N):
    if A[i] == 0:
        a += 1
    elif A[i] > 0:
        b += 1
        B.append(A[i])
        D.append(A[i])
    else:
        c += 1
        C.append(A[i])
        D.append(A[i])
if N-a < K:
    print(0)
    exit()

ans = 1

if c == N and K % 2 == 1:
    C = sorted(C,reverse=True)
    for i in range(K):
        ans *= C[i]
        ans %= mod
    print(ans)
    exit()
if K == N:
    for i in range(N):
        ans *= A[i]
        ans %= mod
    print(ans)
    exit()
if b == 0 and K % 2 == 1 and a > 0:
    print(0)
    exit()

d = b + c
E = [(abs(D[i]),D[i]) for i in range(d)]
E = sorted(E,reverse=True)

if K == 1:
    print(max(A) % mod)
    exit()
if K == 2:
    if N == 3:
        M = max([E[0][1]*E[1][1],E[0][1]*E[2][1],E[1][1]*E[2][1]])
        print(M % mod)
        exit()
    else:
        M = max([E[0][1] * E[1][1], E[0][1] * E[2][1], E[1][1] * E[2][1],E[0][1] * E[3][1],E[1][1] * E[3][1],E[2][1] * E[3][1]])
        print(M % mod)
        exit()



r = 0
if K >= 3:
    for i in range(K-2):
        if E[i][1] < 0:
            r += 1
        ans *= E[i][0]
        ans %= mod

if K == N-1:
    x = E[K-2][1]
    y = E[K-1][1]
    z = E[K][1]
    a1 = x
    a1 *= y
    a2 = x
    a2 *= z
    a3 = y
    a3 *= z
    if r % 2 == 0:
        M = max([a1,a2,a3])
    else:
        M = min([a1,a2,a3])
    print((ans*M) % mod)
    exit()

else:
    x = E[K-2][1]
    y = E[K-1][1]
    z = E[K][1]
    w = E[K+1][1]
    a1 = x
    a1 *= y
    a2 = x
    a2 *= z
    a3 = y
    a3 *= z
    a4 = x
    a4 *= w
    a5 = y
    a5 *= w
    a6 = z
    a6 *= w
    if r % 2 == 0:
        M = max([a1,a2,a3,a4,a5,a6])
    else:
        M = min([a1,a2,a3,a4,a5,a6])
    print((ans*M) % mod)
    exit()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

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

def abssort(A):
    return sorted(A, key = lambda x:abs(x), reverse= True)

tmps = []
A_abs = abssort(A)
for i in range(K):
    # tmp *= A_abs[i]
    tmps.append(A_abs[i])

cnt = 0
for i in range(K):
    if tmps[i] < 0:
        cnt += 1
if cnt % 2 == 0:
    ans = 1
    for i in range(K):
        ans *= tmps[i]
        ans = ans % mod
    print(ans)
    sys.exit()
else:
    tmp_1 = copy.deepcopy(tmps)
    tmp_2 = copy.deepcopy(tmps)
    tmp_1.reverse()
    tmp_2.reverse()
    tmp_2_ = 0
    tmp_1_ = 0
    # -を一つ消す
    for i in range(K):
        if tmp_1[i] < 0:
            tmp_1.remove(tmp_1[i])
            break
    # + を一つたす
    for i in range(K, N):
        if A_abs[i] > 0:
            tmp_1.append(A_abs[i])
            tmp_1_ = 1
            break
    else:
        # +がなかった時
        tmp_1 = []
        tmp_1_ = -1 
        A_abs.reverse()
        for i in range(K):
            tmp_1.append(A_abs[i])

    # +を消して-を追加
    cnt = 0
    for i in range(K):
        if tmp_2[i] > 0:
            tmp_2.remove(tmp_2[i])
            cnt += 1
            break
    if cnt == 1:
        for i in range(K, N):
            if A_abs[i] < 0:
                tmp_2.append(A_abs[i])
                tmp_2_ = 1
                break
        else:
            tmp_2_ = 0
    else:
        tmp_2_ = -1
# print(tmp_1, tmp_2)



tmp_1_m = 1
tmp_2_m = 1
for i in range(K):
    tmp_1_m *= tmp_1[i]
    tmp_1_m = tmp_1_m % mod

if tmp_2_ == 0:
    pass
else:
    for i in range(K):
        tmp_2_m *= tmp_2[i]
        tmp_2_m = tmp_2_m % mod

# print(tmp_1_, tmp_2_)
if tmp_2_ == 0:
    print(tmp_1_m)
elif tmp_1_ == 1 and tmp_2_ == -1:
    print(tmp_1_m)
elif tmp_1_ == -1 and tmp_2_ == 1:
    print(tmp_2_m)
elif tmp_1_ == 1 and tmp_2_ == 1:
    for i in range(K):
        if tmp_1[i] == tmp_2[i]:
            pass
        elif tmp_1[i] > tmp_2[i]:
            print(tmp_2_m)
            sys.exit()
        else:
            print(tmp_1_m)
            sys.exit()
else:
    for i in range(K):
        if tmp_1[i] == tmp_2[i]:
            pass
        elif tmp_1[i] > tmp_2[i]:
            print(tmp_1_m)
            sys.exit()
        else:
            print(tmp_2_m)
            sys.exit()

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
alist = list(map(int,input().split()))
mod = 10**9+7
pnt = 1
abslist = sorted(alist,reverse = True,key = lambda x:abs(x))
noabs = sorted(alist,reverse = True)
pnt = 1
for i in range(k-1):
    pnt *= abslist[i]
print(pnt)
if pnt < 0:
    for j in range(k-1,n):
        if abslist[j] < 0:
            pnt *= abslist[j]
            pnt %= mod
            print(pnt)
            exit()
    
    new = 1
    for i in range(k):
        new *= noabs[i]
    print(new%mod)
    exit()
else:
    for j in range(k-1,n):
        if abslist[j] > 0:
            pnt *= abslist[j]
            pnt %= mod
            print(pnt)
            exit()
    
    new = 1
    for i in range(k):
        new *= noabs[i]
    print(new%mod)
    exit()