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: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, acos, asin, atan, sqrt, tan, cos, pi
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


n, k = LI()
A = LI()
A.sort()
if k % 2 and all([a < 0 for a in A]):
    ret = 1
    A.reverse()
    for i in range(k):
        ret = ret * A[i] % mod
    print(ret)
    exit()

i = 0
ret = A.pop() if k % 2 else 1
while k > 1:
    x = A[i] * A[i + 1]
    y = A[-1] * A[-2]
    if y > x:
        A.pop()
        A.pop()
        ret = ret * y % mod
    else:
        ret = ret * x % mod
        i += 2
    k -= 2
    ret %= mod

print(ret)

Submission status: Accepted

Solution code:
MOD = 10 ** 9 + 7


def mul_mod(x, y, mod):
    return x * y % mod


def main():
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    a.sort(key=lambda x: abs(x), reverse=True)

    res = 1

    if k == 1:
        res = max(a) % MOD
    elif k == n:
        res = 1
        for e in a:
            res *= e
            res %= MOD
    elif max(a) < 0:
        if k % 2 == 1:
            for i in range(n - k, n):
                res *= a[i]
                res %= MOD
        else:
            for i in range(k):
                res *= a[i]
                res %= MOD
    else:
        plus_a = [e for e in a if e >= 0]
        minus_a = [e for e in a if e < 0]

        minus_cnt = min(k, len(minus_a))
        minus_cnt -= minus_cnt % 2
        plus_cnt = k - minus_cnt

        minus_a = minus_a[:minus_cnt]
        minus_a.reverse()

        max_change_cnt = min(minus_cnt, len(plus_a) - plus_cnt)
        max_change_cnt -= max_change_cnt % 2
        change_cnt = 0
        while change_cnt < max_change_cnt:
            if plus_a[plus_cnt + change_cnt] * plus_a[plus_cnt + change_cnt + 1]\
                    <= minus_a[change_cnt] * minus_a[change_cnt + 1]:
                break
            change_cnt += 2

        for i in range(change_cnt, minus_cnt):
            res *= minus_a[i]
            res %= MOD

        for i in range(plus_cnt + change_cnt):
            res *= plus_a[i]
            res %= MOD

    print(res)


main()

Submission status: Accepted

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

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

ans = 1
if k > len(plus) + len(minus):
    ans = 0
elif len(minus) == 0:
    plus.sort(reverse=True)
    for i in range(k):
        ans = (ans * plus[i]) % mod
elif len(plus) == 0:
    if k % 2 == 0:
        minus.sort()
        for i in range(k):
            ans = (ans * minus[i]) % mod
    else:
        if n != len(minus):
            ans = 0
        else:
            minus.sort(reverse=True)
            for i in range(k):
                ans = (ans * minus[i]) % mod
elif k == len(plus) + len(minus) and (len(minus) % 2) == 1:
    if n != len(plus) + len(minus):
        ans = 0
    else:
        for x in plus:
            ans = (ans * x) % mod
        for y in minus:
            ans = (ans * y) % mod
else:
    plus.sort(reverse=True)
    minus.sort()
    i, j = 0, 0
    if k % 2 == 1:
        ans = plus[0]
        i = 1
    while i + j < k:
        tmp_p = plus[i] * plus[i + 1] if i <= len(plus) - 2 else 1
        tmp_m = minus[j] * minus[j + 1] if j <= len(minus) - 2 else 1
        if tmp_p >= tmp_m:
            ans = (ans * (tmp_p % mod)) % mod
            i += 2
        else:
            ans = (ans * (tmp_m % mod)) % mod
            j += 2
print(ans)

Submission status: Accepted

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

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

ans = 1
if k > len(plus) + len(minus):
    ans = 0
elif len(minus) == 0:
    plus.sort(reverse=True)
    for i in range(k):
        ans = (ans * plus[i]) % mod
elif len(plus) == 0:
    if k % 2 == 0:
        minus.sort()
        for i in range(k):
            ans = (ans * minus[i]) % mod
    else:
        if n != len(minus):
            ans = 0
        else:
            minus.sort(reverse=True)
            for i in range(k):
                ans = (ans * minus[i]) % mod
elif k == len(plus) + len(minus) and (len(minus) % 2) == 1:
    if n != k:
        ans = 0
    else:
        for x in plus:
            ans = (ans * x) % mod
        for y in minus:
            ans = (ans * y) % mod
else:
    plus.sort(reverse=True)
    minus.sort()
    i, j = 0, 0
    if k % 2 == 1:
        ans = plus[0]
        i = 1
    while i + j < k:
        tmp_p = plus[i] * plus[i + 1] if i <= len(plus) - 2 else 1
        tmp_m = minus[j] * minus[j + 1] if j <= len(minus) - 2 else 1
        if tmp_p >= tmp_m:
            ans = (ans * (tmp_p % mod)) % mod
            i += 2
        else:
            ans = (ans * (tmp_m % mod)) % mod
            j += 2
print(ans)

Submission status: Accepted

Solution code:
import sys
n,k=map(int,input().split())
A=[]
mod=10**9+7

zero=0
a=list(map(int,input().split()))
for i in range(n):
    if a[i]>0:
        A.append([a[i],0])
    elif a[i]<0:
        A.append([-a[i],1])
    else:
        zero+=1        
if k>n-zero:
    print(0)
    sys.exit()

A=list(reversed(sorted(A)))
cnt=0
for i in range(k):
    cnt+=A[i][1]
chk=0
for i in range(n-zero):
    chk+=A[i][1]    

if cnt%2==0:
    ans=1
    for i in range(k):
        ans=ans*A[i][0]%mod
    print(ans)
elif chk==n-zero:
    if zero>0:
        print(0)
        sys.exit()
    ans=1
    for i in range(k):
        ans=ans*A[n-i-1][0]%mod
    print((-ans)%mod)
elif k==n-zero:
    ans=1
    if zero>0:
        print(0)
    else:
        for i in range(k):
            ans=ans*A[i][0]%mod
        print((-ans)%mod)
        
else:
    if A[k][1]==0:
        p=A[k][0]
        m=0
        for i in range(k+1,n-zero):
            if A[i][1]==1:
                m=A[i][0]
                break
    else:
        m=A[k][0]
        p=0
        for i in range(k+1,n-zero):
            if A[i][1]==0:
                p=A[i][0]
                break
    #print(m,p)
    if A[k-1][1]==0:
        l=0
        Xl=-1
        for i in range(k-1):
            if A[k-i-2][1]==1:
                l=A[k-i-2][0]
                Xl=k-i-2
                break
        #print(l,k)
        if m*l>p*A[k-1][0] or Xl==-1:
            ans=1
            for i in range(k-1):
                ans=ans*A[i][0]%mod
            ans=ans*m%mod
            print(ans)
        else:
            ans=1
            for i in range(k):
                if i==Xl:
                    continue
                ans=ans*A[i][0]%mod 
            ans=ans*p%mod
            print(ans)
    else:
        l=0
        Xl=-1
        for i in range(k-1):
            if A[k-i-2][1]==0:
                l=A[k-i-2][0]
                Xl=k-i-2
                break
        #print(l,k)
        if p*l>m*A[k-1][0] or Xl==-1:
            ans=1
            for i in range(k-1):
                ans=ans*A[i][0]%mod
            ans=ans*p%mod
            print(ans)
        else:
            ans=1
            for i in range(k):
                if i==Xl:
                    continue
                ans=ans*A[i][0]%mod 
            ans=ans*m%mod
            print(ans)

Submission status: Accepted

Solution code:
import numpy as np
N,K = map(int,input().split())
import math
A = list(map(int,input().split()))
flag = 0
if 0 in A:
    flag = 1
A.sort()

plus = list(filter(lambda x:x>0, A))[::-1]
plus = list(map(lambda x:np.longdouble(math.log(x,10000000)),plus))
from itertools import accumulate
acc_plu = [0] +  list(accumulate(plus))
minu = filter(lambda x:x<0, A)
minu = list(map(lambda x:np.longdouble(math.log(-x,10000000)),minu))
acc_min = [0] +  list(accumulate(minu))


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

ans = 1
if cand == []:
    if flag:
        print(0)
        exit()
    cnt = 0
    #マイナス確定
    abss = sorted(list(map(lambda x :abs(x),A)))
    for x in abss:
        if cnt == K:break
        ans *= x
        ans %= MOD
        cnt += 1
    ans *= -1
    ans %= MOD
    print(ans)
else:
    cand = sorted(cand)[::-1]
    plus = list(filter(lambda x:x>0, A))[::-1]
    minu = list(filter(lambda x:x<0, A))
    c = cand[0]
    ans = 1
    for i in range(c[1]):
        ans *= plus[i]
        ans %= MOD
    for i in range(c[2]):
        ans *= minu[i]
        ans %= MOD
    print(ans)

Submission status: Accepted

Solution code:
def main():
    n,k = map(int,input().split())
    A = list(map(int,input().split()))
    MOD = 10**9+7


    B = []
    flg_m = 0
    flg_p = 0

    for a in A:
        if a < 0:
            B.append([abs(a),-1])
            flg_m = 1
        else:
            B.append([abs(a),1])
            flg_p = 1

        b = 0
    ans = -10**9
    if k == 1:
        for a in A:
            ans = max(ans,a)
        print(ans)
        exit()

    B.sort(reverse=True)
    # print(B)
    if flg_p == 0 and k%2 == 1:
        B.sort()
        L = B[:k]
        ans = cal_ans(L)
        ans *=-1
        print(ans%MOD)
        exit()
    elif flg_p * flg_m == 0:
        L = B[:k]
        ans = cal_ans(L)
        print(ans)
        exit()

    flg_p = 0
    flg_m = 0
    flg_lm = 0
    flg_lp = 0
    # print(B)
    for i,(n,sign) in enumerate(B):
        if i < k:
            if sign == -1:
                flg_lp = 1
                last_m = n
            else:
                flg_lm = 1
                last_p = n
        else:
            if sign == -1:
                if flg_m == 0:
                    first_m = n
                    flg_m = 1
            else:
                if flg_p == 0:
                    first_p = n
                    flg_p = 1

    L = B[:k]
    ans = cal_ans(L)
    c = 0
    for n,sign in L:
        if sign == -1:
            c += 1
    if c % 2 == 0:
        print(ans)
        exit()
    if flg_p == 1 and flg_m == 1 and flg_lp == 1 and flg_lm == 1:
        if first_p * last_p >= first_m*last_m:
            a = first_p
            b = last_m
        else:
            a = first_m
            b = last_p
    elif flg_p == 1:
            a = first_p
            b = last_m
    elif flg_m == 1:
            a = first_m
            b = last_p
    else:
        ans = 1
        for a in A:
            ans *= a
            ans %= MOD
        print(ans)
        exit()


    ans *= a
    ans %= MOD
    ans *= pow(b,MOD-2,MOD)
    ans %= MOD
    print(ans)

def cal_ans(L):
    MOD = 10**9+7
    ans = 1
    for i,j in L:
        ans *= i
        ans %= MOD
    return ans



main()

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
a = list(map(int, input().split()))

mod=10**9+7
a.sort()

if n==k:
    ans=1
    for num in a:
        ans*=num
        ans%=mod
    print(ans)
    exit()

if a[-1]<0: # all a is minus
    if k%2==1: # ans is minus
        a.sort(reverse=True)
        ans=1
        for num in a[:k]:
            ans*=num
            ans%=mod
        print(ans)
        exit()

# ans>=0

ans=1
if k%2==1:
    ans=a[-1]
    a.pop(-1)
    k-=1

pz_a=[]
m_a=[]

for num in a:
    if num<0:
        m_a.append(num)
    else:
        pz_a.append(num)
pz_a.sort(reverse=True)

c2_a=[]
lastnum=-1
for i in range(len(pz_a)):
    num1=pz_a[i]
    if lastnum==-1:
        lastnum=num1
    else:
        c2_a.append(lastnum*num1)
        lastnum=-1

lastnum=1
for i in range(len(m_a)):
    num1=m_a[i]
    if lastnum==1:
        lastnum=num1
    else:
        c2_a.append(lastnum*num1)
        lastnum=1

c2_a.sort(reverse=True)

for num in c2_a[:k//2]:
    ans*=num
    ans%=mod

print(ans)

Submission status: Accepted

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

def main():
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

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

    ans = 1
    ma = max(A)
    if ma <= 0 and K % 2:
        # 最大値が0以下でKが奇数の場合
        x = sorted(A,reverse=True)
        # 大きいほうからK個の積
        for i in range(K):
            ans = (ans * x[i]) % MOD
        print(ans)
        return

    # 絶対値でソート
    x = sorted(A, key=lambda x: abs(x), reverse=True)
    m = 0
    # 絶対値が大きいほうからK個の積
    for i in range(K):
        ans = (ans * x[i]) % MOD
        if x[i] < 0: m += 1

    # K==Nか、マイナスが偶数、答えが0ならそのままリターン
    if K == N or m % 2 == 0 or ans == 0:
        print(ans)
        return
    # K+1個目が0なら、0でリターン
    if x[K] == 0:
        print(0)
        return

    # K個目まですべてマイナスなら
    if m == K:
        # K番目とK+1以降の最大値とを入れ替え
        ans = (ans * pow(x[K-1],MOD-2,MOD) * max(x[K:])) % MOD

    else:
        K1 = -1
        # K+1番目と符号が反対で絶対値が最大の数をK+2番目以降で探す
        for i in range(K+1,N):
            if x[K] * x[i] < 0:
                K1 = i
                break

        f0 = 0.0
        f1 = 0.0
        i0 = -1
        i1 = -1
        # K番目以内でK+1番目と符号が反対で最小の数を探す
        for i in range(K-1,-1,-1):
            if x[i] * x[K] < 0:
                i0 = i
                # 入れ替えた時の減少率
                f0 = x[K] / x[i]
                break

        if K1 >= 0:
            # K1が存在するとき、K番目以内でK1番目と符号が反対で最小の数を探す
            for i in range(K-1,-1,-1):
                if x[i] * x[K1] < 0:
                    i1 = i
                    f1 = x[K1] / x[i]
                    break

        if abs(f0) >= abs(f1):
            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: Accepted

Solution code:
import sys

MOD = 10**9 + 7

def read_int():
    line = sys.stdin.readline().rstrip('\n')
    return int(line)

def read_int_list():
    line = sys.stdin.readline().rstrip('\n')
    return [int(e) for e in line.split(' ')]

def sign(n):
    if n > 0:
        return 1
    if n < 0:
        return -1
    return 0

def prod(A, K, add, remove):
    prod = 1
    for i in range(K):
        if i == remove:
            continue
        prod *= abs(A[i])
        prod %= MOD
    if add != None:
        prod *= abs(A[add])
        prod %= MOD
    return prod

N, K = read_int_list()
A = read_int_list()

A.sort(key=lambda i: -abs(i))

last_plus = None
last_minus = None
sig = 1
for i in range(K):
    sig *= sign(A[i])
    if A[i] > 0:
        last_plus = i
    if A[i] < 0:
        last_minus = i
remove_plus = None
add_plus = None
remove_minus = None
add_minus = None
if sig < 0:
    for i in range(K, N):
        if A[i] > 0 and last_minus != None and remove_minus == None:
            remove_minus = last_minus
            add_minus = i
            sig = 1
        elif A[i] < 0 and last_plus != None and remove_plus == None:
            remove_plus = last_plus
            add_plus = i
            sig = 1
        elif A[i] == 0:
            if sig < 0:
                sig = 0
            break

if sig == 0:
    print(0)
elif sig > 0:
    if remove_plus != None and remove_minus != None:
        if abs(A[remove_plus]*A[add_minus]) > abs(A[remove_minus]*A[add_plus]):
            ap = prod(A, K, add_minus, remove_minus)
        else:
            ap = prod(A, K, add_plus, remove_plus)
    elif remove_plus != None:
        ap = prod(A, K, add_plus, remove_plus)
    else:
        ap = prod(A, K, add_minus, remove_minus)
    print(ap)
else:
    ap = prod(A[::-1], K, None, None)
    print((MOD-ap) % MOD)

Submission status: Accepted

Solution code:
n,k,*a=map(int,open(0).read().split())
a.sort()
p=a.pop
s=b=~k%2or p()
i=0
while k>1:
 x=a[i]*a[i+1]
 if x*b>a[-1]*a[-2]*b:s*=x;i+=2
 else:s*=p()*p()
 s%=10**9+7;k-=2
print(s)

Submission status: Accepted

Solution code:
n,k,*a=map(int,open(i:=0).read().split())
a.sort()
p=a.pop
s=b=~k%2or p()
while k>1:
 if(x:=a[i]*a[i+1])*b>a[-1]*a[-2]*b:s*=x;i+=2
 else:s*=p()*p()
 s%=10**9+7;k-=2
print(s)

Submission status: Accepted

Solution code:
mod=10**9+7
n,k=map(int,input().split())
arr=list(map(int,input().split()))
cnt_plus=0
cnt_zero=0
cnt_minus=0
arr_plus=[]
arr_minus=[]
for i in range(n):
  if arr[i]>0:
    cnt_plus+=1
    arr_plus.append(arr[i])
  elif arr[i]<0:
    cnt_minus+=1
    arr_minus.append(-arr[i])
  else:
    cnt_zero+=1
if cnt_plus+cnt_minus<k:
  print(0)
  exit()
if k==n:
  if cnt_zero!=0:
    print(0)
  else:
    ans=1
    for i in range(cnt_plus):
      ans*=arr_plus[i]
      ans%=mod
    for i in range(cnt_minus):
      ans*=arr_minus[i]
      ans%=mod
    if cnt_minus%2==0:
      print(ans)
    else:
      print((-ans)%mod)
  exit()
if cnt_plus==0 and k%2==1:
  if cnt_zero!=0:
    print(0)
  else:
    arr_minus=sorted(arr_minus)
    tmp=1
    for i in range(k):
      tmp*=arr_minus[i]
      tmp%=mod
    print((-tmp)%mod)
  exit()
else:
  arr_plus=sorted(arr_plus,reverse=True)
  arr_minus=sorted(arr_minus,reverse=True)
  if k%2==0:
    ans=1
    pos_plus=0
    pos_minus=0
    cnt=0
  else:
    ans=arr_plus[0]
    pos_plus=1
    pos_minus=0
    cnt=1
  while cnt<k:
    cand1=0
    if pos_plus<=cnt_plus-2:
      cand1=arr_plus[pos_plus]*arr_plus[pos_plus+1]      
    cand2=0
    if pos_minus<=cnt_minus-2:
      cand2=arr_minus[pos_minus]*arr_minus[pos_minus+1]
    if cand1>=cand2:
      pos_plus+=2
      ans*=cand1
      ans%=mod
    else:
      pos_minus+=2
      ans*=cand2
      ans%=mod
    cnt+=2
  print(ans)
  exit()

Submission status: Accepted

Solution code:
mod=10**9+7
n,k=map(int,input().split())
arr=list(map(int,input().split()))
cnt_plus=0
cnt_zero=0
cnt_minus=0
arr_plus=[]
arr_minus=[]
for i in range(n):
  if arr[i]>0:
    cnt_plus+=1
    arr_plus.append(arr[i])
  elif arr[i]<0:
    cnt_minus+=1
    arr_minus.append(-arr[i])
  else:
    cnt_zero+=1
if cnt_plus+cnt_minus<k:
  print(0)
  exit()
if k==n:
  if cnt_zero!=0:
    print(0)
  else:
    ans=1
    for i in range(cnt_plus):
      ans*=arr_plus[i]
      ans%=mod
    for i in range(cnt_minus):
      ans*=arr_minus[i]
      ans%=mod
    if cnt_minus%2==0:
      print(ans)
    else:
      print((-ans)%mod)
  exit()
if cnt_plus==0 and k%2==1:
  if cnt_zero!=0:
    print(0)
  else:
    arr_minus=sorted(arr_minus)
    tmp=1
    for i in range(k):
      tmp*=arr_minus[i]
      tmp%=mod
    print((-tmp)%mod)
  exit()
else:
  arr_plus=sorted(arr_plus,reverse=True)
  arr_minus=sorted(arr_minus,reverse=True)
  if k%2==0:
    ans=1
    pos_plus=0
    pos_minus=0
    cnt=0
    while cnt<k:
      cand1=0
      if pos_plus<=cnt_plus-2:
        cand1=arr_plus[pos_plus]*arr_plus[pos_plus+1]      
      cand2=0
      if pos_minus<=cnt_minus-2:
        cand2=arr_minus[pos_minus]*arr_minus[pos_minus+1]
      if cand1>=cand2:
        pos_plus+=2
        ans*=cand1
        ans%=mod
      else:
        pos_minus+=2
        ans*=cand2
        ans%=mod
      cnt+=2
    print(ans)
  else:
    ans=arr_plus[0]
    pos_plus=1
    pos_minus=0
    cnt=1
    while cnt<k:
      cand1=0
      if pos_plus<=cnt_plus-2:
        cand1=arr_plus[pos_plus]*arr_plus[pos_plus+1]      
      cand2=0
      if pos_minus<=cnt_minus-2:
        cand2=arr_minus[pos_minus]*arr_minus[pos_minus+1]
      if cand1>=cand2:
        pos_plus+=2
        ans*=cand1
        ans%=mod
      else:
        pos_minus+=2
        ans*=cand2
        ans%=mod
      cnt+=2
    print(ans)
  exit()

Submission status: Accepted

Solution code:

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

  mod = 10 ** 9 + 7

  if n == k:
    ans = 1
    for num in input().split():
      ans = (ans * int(num)) % mod

    print(ans % mod)
    return

  plus = []
  minus = []
  for num in input().split():
    num = int(num)
    if num >= 0:
      plus.append(num)
    else:
      minus.append(num)

  pn = len(plus)
  mn = len(minus)

  if pn == 0 and k % 2 == 1:
    minus.sort(reverse = True)
    ans = 1
    for i in range(k):
      ans = (-ans * minus[i]) % mod

    print((-ans) % mod)
    return


  plus.sort(reverse = True)
  minus.sort()

  pi = 0
  mi = 0

  while k > 0:
    if pi + 1 == pn:
      if k % 2 == 0:
        mi += k
      else:
        pi += 1
        mi += k - 1

      break

    if pi == pn:
      mi += k
      break

    if mi + 1 >= mn:
      pi += k
      break

    if k == 1 or plus[pi] * plus[pi + 1] >= minus[mi] * minus[mi + 1]:
      pi += 1
      k -= 1
    else:
      mi += 2
      k -= 2

  ans = 1
  for i in range(pi):
    ans = (ans * plus[i]) % mod

  for i in range(mi):
    ans = (-ans * minus[i]) % mod

  print(ans % mod)


main()

Submission status: Accepted

Solution code:
import sys

M = 10 ** 9 + 7
N, K = map(int, input().split())

p_list = []
n_list = []
z_count = 0

for A in map(int, input().split()):
	if A < 0:
		n_list.append(A)
	elif A > 0:
		p_list.append(A)
	else:
		z_count += 1

p_list.sort()
n_list.sort()

#print(p_list)
#print(n_list)

if len(p_list) + len(n_list) < K:
	print(0)
else:
	values = []
	
	if len(p_list) + len(n_list) == K:
		values = p_list + n_list
		n_count = 0
		for v in values:
			if v < 0:
				n_count += 1
		if n_count % 2 == 1 and z_count > 0:
			values = [0]
	elif len(p_list) == 0 and K % 2 == 1:
		if z_count > 0:
			values = [0]
		else:
			for i in range(min(len(n_list), K)):
				values.append(n_list.pop())
	else:
		n_list.reverse()
		values_pair = []
		values_left = None
		values_left_count = 0
		if len(p_list) >= K:
			if K % 2 == 1:
				values_left = p_list.pop()
				values_left_count = 1
				p_count = K - 1
			else:
				p_count = K
			
			while len(values_pair) * 2 + values_left_count < K:
				v1 = p_list.pop()
				v2 = p_list.pop()
				values_pair.append((v1 * v2, v1, v2))
		
		else:
			if (K - len(p_list)) % 2 == 1 and len(p_list) > 0:
				p_count = len(p_list) - 1
			else:
				p_count = len(p_list)
			
			if p_count % 2 == 1:
				values_left = p_list.pop()
				values_left_count = 1
				p_count -= 1
			
			for i in range(0, p_count - 1, 2):
				v1 = p_list.pop()
				v2 = p_list.pop()
				values_pair.append((v1 * v2, v1, v2))
			
			while len(values_pair) * 2 + values_left_count < K:
				v1 = n_list.pop()
				v2 = n_list.pop()
				values_pair.append((v1 * v2, v1, v2))
		
		values_pair.sort()
		
#		print(values_pair)
		
		i = 0
		for i in range(len(values_pair)):
			if len(n_list) < 2:
				break
			elif values_pair[i][0] < n_list[-1] * n_list[-2]:
				v1 = n_list.pop()
				v2 = n_list.pop()
				values_pair[i] = (v1 * v2, v1, v2)
			else:
				break
		if values_left != None:
			values.append(values_left)
		
		for prod, v1, v2 in values_pair:
			values.append(v1)
			values.append(v2)
	
#	print(values)
	total = 1
	for v in values:
		total = (total * v) % M
#		total = (total * v)
	print(total)

Submission status: Accepted

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

mod = 10**9+7
ans = 1
mi = []
pl = []
for a in A:
    if a < 0:
        mi.append(a)
    else:
        pl.append(a)

if N == K:
    for a in A:
        ans *= a
        ans %= mod
    print(ans)
    exit()
if pl == []:
    if K%2:
        for k in range(K):
            ans *= mi[-1-k]
            ans %= mod
    else:
        for k in range(K):
            ans *= mi[k]
            ans %= mod
    print(ans)
    exit()

pl = pl[::-1]

ip = 0
im = 0
if K % 2:
    ans = pl[0]
    ip += 1
    K -= 1

while K > 0:
    check = True
    if ip + 2 <= len(pl):
        x = pl[ip]*pl[ip+1]
    else:
        x = 1
    if im + 2 <= len(mi):
        y = mi[im]*mi[im+1]
    else:
        check = False
        y = 1

    if x >= y or check == False:
        ans *= x
        ans %= mod
        ip += 2
    else:
        ans *= y
        ans %= mod
        im += 2
    K -= 2
print(ans)

Submission status: Accepted

Solution code:
n, k = (int(x) for x in input().split())
A = list(int(x) for x in input().split())
MOD = 10**9 + 7
A.sort()

l = 0
r = n - 1
flag = False  # マイナスになってしまうかフラグ
ans = 1
if k % 2 == 1:
    ans = A[r]
    r -= 1
    k -= 1
    if ans < 0:
        flag = True


if flag:  # どうしてもマイナスになってしまう場合(kが奇数で要素すべてがマイナスの場合)
    while k:
        ans *= A[r] * A[r - 1] % MOD
        ans %= MOD
        r -= 2
        k -= 2
else:  # 必ず0以上にできる場合
    while k:
        x = A[l] * A[l + 1]
        y = A[r] * A[r - 1]
        if x > y:
            ans *= x % MOD
            ans %= MOD
            l += 2
        else:
            ans *= y % MOD
            ans %= MOD
            r -= 2
        k -= 2

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)

MOD = 10**9+7


def main(input, print):
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    plus = []
    neg = []
    for i in range(n):
        if a[i] < 0:
            neg.append(a[i])
        else:
            plus.append(a[i])
    is_ans_plus = False
    if len(plus) > 0:
        if n == k:
            is_ans_plus = len(neg) % 2 == 0
        else:
            is_ans_plus = True
    else:
        is_ans_plus = k % 2 == 0
    ans = 1
    if is_ans_plus:
        neg = sorted(neg, key=abs, reverse=True)
        plus = sorted(plus, key=abs, reverse=True)
        pair = []
        for i in range(1, len(neg), 2):
            pair.append(neg[i-1]*neg[i])
        s = 1
        if k % 2 == 1:
            ans = plus[0]
            s = 2
        for i in range(s, len(plus), 2):
            pair.append(plus[i-1]*plus[i])
        pair = sorted(pair, reverse=True)
        for i in range(k//2):
            ans = ans * pair[i] % MOD
    else:
        a = sorted(a, key=abs)
        for i in range(k):
            ans = ans * a[i] % MOD

    print(ans)


if __name__ == '__main__':
    main(sys.stdin.readline, print)

Submission status: Accepted

Solution code:
n, k = (int(x) for x in input().split())
A = list(int(x) for x in input().split())
MOD = 10**9 + 7
A.sort()

l = 0
r = n - 1
sign = 1  # 1 or -1
ans = 1
if k % 2 == 1:
    ans = A[r]
    r -= 1
    k -= 1
    if ans < 0:
        sign = -1

while k:
    x = A[l] * A[l + 1]
    y = A[r] * A[r - 1]
    if x * sign > y * sign:
        ans *= x % MOD
        ans %= MOD
        l += 2
    else:
        ans *= y % MOD
        ans %= MOD
        r -= 2
    k -= 2

print(ans)

Submission status: Accepted

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

if max(a) < 0:
    a.sort()
    ans = 1
    if k % 2 == 0:
        for e in a[:k]:
            ans *= e
            ans %= mod
    else:
        for e in a[-k:]:
            ans *= e
            ans %= mod

    print(ans)

elif k == n:
    ans = 1
    for e in a:
        ans *= e
        ans %= mod

    print(ans)

else:
    neg = []
    pos = []
    for e in a:
        if e < 0:
            neg.append(e)
        else:
            pos.append(e)

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

    ans = 1
    if k % 2:
        ans *= pos.pop(0)
        k -= 1

    nums = [e1 * e2 for e1, e2 in zip(neg[::2], neg[1::2])]
    nums += [e1 * e2 for e1, e2 in zip(pos[::2], pos[1::2])]

    nums.sort(reverse=True)
    for e in nums[:k//2]:
        ans *= e
        ans %= mod

    print(ans)

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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

S = []
T = []
for a in A:
    if a < 0:
        T.append(a)
    else:
        S.append(a)

ls = len(S)
lt = len(T)
ok = False

if ls > 0:
    if N == K:
        ok = lt % 2 == 0
    else:
        ok = True
else:
    ok = K % 2 == 0

ans = 1
if not ok:
    A = sorted(A, key=lambda x: abs(x))
    for a in A[:K]:
        ans *= a
        ans %= MOD
else:
    S = sorted(S)
    T = sorted(T, reverse=True)
    if K % 2 == 1: # if K is odd, the answer has at least one positive number.
        ans *= S.pop()
        ans %= MOD
    p = []
    # the num of negatives must be even, so positives must do the same
    # thus, we can pop 2 items at one time.
    while len(S) >= 2:
        x = S.pop()  
        y = S.pop()
        p.append(x * y)
    while len(T) >= 2:
        x = T.pop()  
        y = T.pop()
        p.append(x * y)
    p = sorted(p, reverse=True)
    for i in range(K // 2):
        ans *= p[i]
        ans %= MOD
print(ans % MOD)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
A = list(map(int,input().split()))

mod = 10**9 + 7

A.sort(key = lambda x:abs(x),reverse = True)
ans = 1
last = -1
lastp = -1
cnt = 0
for a in A:
    if a >= 0:break
else:
    if k&1:
        for i in range(k):
            ans *= A[n-i-1]
            ans %= mod
    else:
        for i in range(k):
            ans *= A[i]
            ans %= mod
    print(ans)
    exit()
for i in range(k):
    ans *= A[i]
    ans %= mod
    if A[i] < 0:
        last = i
        cnt += 1
    if A[i] > 0:
        lastp = i
if n == k:
    print(ans%mod)
    exit()
if cnt&1:
    first = 0
    firstp = 0
    for a in A[k:]:
        if a > 0 and firstp == 0:
            firstp = a
        if a < 0 and first == 0:
            first = a
    if first == 0 and firstp == 0:
        ans = 0
    elif first == 0 or lastp == -1:
        ans *= pow(A[last],mod-2,mod)*firstp%mod
        ans %= mod
    elif firstp == 0:
        ans *= pow(A[lastp],mod-2,mod)*first%mod
        ans %= mod
    else:
        if A[lastp]*firstp <= A[last]*first:
            ans *= pow(A[lastp],mod-2,mod)*first%mod
            ans %= mod
        else:
            ans *= pow(A[last],mod-2,mod)*firstp%mod
            ans %= mod
print(ans%mod)