Problem:


Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

8 5
-9 -7 -4 -3 1 2 3 4

Sample Output 4

10



Sample input:
5 3
-30 -10 10 20 50


Sample output:
40

Submission status: Accepted

Solution code:
import math
from math import gcd,pi,sqrt
INF = float("inf")

import sys
sys.setrecursionlimit(10**6)
import itertools
from collections import Counter,deque
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]


def main():
    n, k = i_map()
    x = i_list()

    l = []
    r = []

    for i in x:
        if i < 0:
            l.append(-i)
        else:
            r.append(i)
    l.reverse()

    # if len(l) > 0:
    #     L = [l[0]]
    #     if len(l) > 1:
    #         for i in range(1, len(l)):
    #             L.append(L[i-1]+l[i])
    #
    # if len(r) > 0:
    #     R = [r[0]]
    #     if len(r) > 1:
    #         for i in range(1, len(r)):
    #             R.append(R[i-1]+r[i])


    R_len = len(r)
    L_len = len(l)

    ans = INF
    for i,j in enumerate(l):
        if R_len >= k - i - 1:
            if R_len == 0:
                ans = min(ans, j)
            else:
                ans = min(ans,2*j+r[k-i-2])

    for i,j in enumerate(r):
        if L_len >= k - i - 1:
            if L_len == 0:
                ans = min(ans,j)
            else:
                ans = min(ans,2*j+l[k-i-2])

    print(ans)


if __name__=="__main__":
    main()

Submission status: Accepted

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

ans = float('inf')
for i in range(n-k+1):
    ans = min(ans, min(abs(x[i]) + abs(x[i+k-1]-x[i]), abs(x[i+k-1]) + abs(x[i+k-1]-x[i])))
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

    zero_ind = bisect_left(x, 0)
    
    if zero_ind == 0:
        print(x[k-1])
        exit()
    elif zero_ind == n:
        print(-x[-k])
        exit()

    if x[zero_ind] == 0:
        x.pop(zero_ind)
        n -= 1
        k -= 1
    
    ans = float('inf')

    # only go to left
    if zero_ind >= k:
        ans = -x[zero_ind - k]

    # only go to right
    if n - zero_ind >= k and ans > x[zero_ind + k - 1]:
        ans = x[zero_ind + k - 1]

    # go to left and go to right
    for i in range(max(0, zero_ind - k + 1), zero_ind):
        if k+i-1 < n and ans > -2 * x[i] + x[k+i-1]:
            ans = -2 * x[i] + x[k+i-1]

    # go to right and go to left
    for i in range(zero_ind, min(n, zero_ind+k)):
        if 0 <= i-k+1 and ans > 2 * x[i] - x[i-k+1]:
            ans = 2 * x[i] - x[i-k+1]

    print(ans)

main()

Submission status: Accepted

Solution code:
import sys
# sys.setrecursionlimit(100000)


def input():
    return sys.stdin.readline().strip()


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


def main():
    n, k = input_int_list()
    X = input_int_list()
    ans = float("inf")
    for i in range(0, n - k + 1):
        tmp_min = X[i]
        tmp_max = X[i + k - 1]
        if tmp_max <= 0:
            tmp = abs(tmp_min)
        elif tmp_min >= 0:
            tmp = abs(tmp_max)
        else:
            tmp = min(abs(tmp_max), abs(tmp_min)) * 2 + max(abs(tmp_max), abs(tmp_min))
        ans = min(tmp, ans)
    print(ans)
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def perm(n,mod=None):
    ans = 1
    for i in range(1,n+1):
        ans *= i
        if mod!=None:
            ans %= mod
    return ans
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    return C

N,K=mint()
X=lint()
minus=[]
plus=[0]
for x in X:
    if x<0:
        minus.append(-x)
    else:
        plus.append(x)
minus.append(0)
P=len(plus)-1
M=len(minus)-1
ans=INF
for i in range(K+1):
    p = INF if K-i>P else plus[K-i]
    m = INF if i>M else minus[M-i]
    ans=min(ans,p+m+min(p,m))
print(ans)

Submission status: Accepted

Solution code:
from sys import stdin

def getval():
    n,k = map(int,input().split())
    x = list(map(int,input().split()))
    return n,k,x

def main(n,k,x):
    idx = k-1
    ans = 0
    if x[0]>=0:
        ans = x[idx]
    elif x[idx]<=0:
        ans = abs(x[0])
    else:
        ans = min(abs(x[0]),abs(x[idx]))*2+max(abs(x[0]),abs(x[idx]))
    for i in range(k,n):
        temp = 0
        #print(ans)
        if x[i-k+1]>=0:
            temp = x[i]
        elif x[i]<=0:
            temp = abs(x[i-k+1])
        else:
            temp = min(abs(x[i]),abs(x[i-k+1]))*2+max(abs(x[i]),abs(x[i-k+1]))
        ans = min(ans,temp)
    print(ans)


if __name__=="__main__":
    n,k,x = getval()
    main(n,k,x)

Submission status: Accepted

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

tp = N
for i in range(N):
    if x[i] >= 0:
        tp = i
        break
    x[i] *= -1

s = max(0, tp-K+1)
g = min(tp-1, N-K)

ans = float("INF")
if K <= tp:
    ans = min(ans, x[tp-K])
if K <= N - tp:
    ans = min(ans, x[tp+K-1])

for i in range(s, g+1):
    ans = min(ans, x[i] + x[i+K-1] + min(x[i], x[i+K-1]))
    #print(x[i], x[i+K-1])

print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
X=list(map(int,input().split()))
answers=[]
whole=0
for n in range(N-K+1):
    if X[K-1+n]>0 and X[n]<0:
        whole += (X[K - 1 + n] - X[n])
        whole+=min(X[K-1+n],-X[n])
    elif X[K-1+n]<0:
        whole-=X[n]
    elif X[n]>0:
        whole+=X[K-1+n]
    answers.append(whole)
    whole=0
print(min(answers))

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
x = list(map(int,input().split()))
mi = 10 ** 18
for i in range(N-K+1):
    l = x[i]
    r = x[i+K-1]
    lr = abs(l)+abs(l-r)
    rl = abs(r)+abs(l-r)
    mi = min(mi,min(lr,rl))
print(mi)

Submission status: Accepted

Solution code:
import sys
N,K = map(int,input().split())
lsx = list(map(int,input().split()))
if 0 in lsx:
    K = K-1
    lsx.remove(0)
if bool(lsx) == False or K == 0:
    print(0)
    sys.exit()
lshu = []
sei = len(lsx)
for i in range(len(lsx)):
    if lsx[i] < 0:
        lshu.append(lsx[i])
    else:
        sei = i
        break
lssei = lsx[sei:]
lenhu = len(lshu)
lensei = len(lssei)
lshu2 = [abs(lshu[i]) for i in range(lenhu-1,-1,-1)]
dishu = [0] + lshu2
dissei = [0] + lssei
ans = 10*10**8
for i in range(K+1):
    if i <= lenhu and K-i <= lensei:
        ans = min(ans,2*dishu[i]+dissei[K-i],dishu[i]+2*dissei[K-i])
print(ans)

Submission status: Accepted

Solution code:
n,k=[int(i) for i in input().split()]
x=[int(i) for i in input().split()]

# ==================================================-
# 二分探索
# functionを満たす,search_listの最大の要素を出力
# 【注意点】searchリストの初めの方はfunctionを満たし、後ろに行くにつれて満たさなくなるべき
import math
import sys
sys.setrecursionlimit(10**9)
def binary_research(start,end,function):
    if start==end:
        return start
    middle=math.ceil((start+end)/2)
    if function(middle):
        start=middle
    else:
        end=middle-1
    return binary_research(start, end, function)
positive=[]
negative=[]
zero=False


for i in x:
    if i<0:
        negative.append(abs(i))
    elif i>0:
        positive.append(i)
    else:
        zero=True
positive.sort()
negative.sort()


def function(time):
    if time==-1:
        return True
    ans_list=[]
    ans=0
    if zero:
        ans+=1
    for i in positive:
        if i<=time:
            ans_list.append(i)
            ans+=1
        else:
            break
    negative_list=[]
    for i in negative:
        if i<=time:
            negative_list.append(i)
        else:
            break
    negative_list=negative_list[::-1]
    newans=ans
    while negative_list:
        newans,ans_list,negative_list=function2(ans_list,negative_list,newans,time)
        ans=max(ans,newans)
        if ans_list==[]:
            break
        else:
            ans_list.pop()
            newans-=1
    if ans>=k:
        return False
    return True



def function2(ans_list,negative_list,ans,time):
    if ans_list==[]:
        max_num=0
    else:
        max_num=ans_list[-1]
    remain_time=time-max_num*2
    while negative_list:
        i=negative_list.pop()
        if max_num==0:
            if i<=remain_time:
                ans+=1
        elif max_num+i+min(i,max_num)<=time:
            ans+=1
        else:
            negative_list.append(i)
            break
    return ans,ans_list,negative_list


print(binary_research(-1,3*10**8+1,function)+1)

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    X = list(map(int, input().split()))
    P = []
    M = []
    for x in X:
        if x < 0:
            M.append(-1 * x)
        else:
            P.append(x)
    M.reverse()

    if len(P) == 0:
        print(M[K - 1])
        exit()
    elif len(M) == 0:
        print(P[K - 1])
        exit()

    ans = 10 ** 10
    for i, m in enumerate(M, start=1):
        d = None
        if i == K + 1:
            break
        elif i == K:
            d = m
        else:
            p_idx = K - i - 1
            if p_idx >= len(P):
                continue
            else:
                d = m * 2 + P[p_idx]
        if d < ans:
            ans = d

    for i, p in enumerate(P, start=1):
        d = None
        if i == K + 1:
            break
        elif i == K:
            d = p
        else:
            m_idx = K - i - 1
            if m_idx >= len(M):
                continue
            else:
                d = p * 2 + M[m_idx]
        if d < ans:
            ans = d

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
xlst = list(map(int, input().split()))
minus = []
plus = []
for x in xlst:
    if x < 0:
        minus.append(-1 * x)
    elif x > 0:
        plus.append(x)
    else:
        k -= 1
if k == 0:
    print(0)
    exit()
minus.append(0)
minus = minus[::-1]
plus = [0] + plus
ans = 10 ** 20
ml = len(minus)
pl = len(plus)

pos = min(k, ml - 1)
while 1:
    mm = minus[pos]
    pp = plus[k - pos]
    ans_tmp = max(mm, pp) + min(mm, pp) * 2
    ans = min(ans, ans_tmp)
    pos -= 1
    if pos == -1 or k - pos == pl:
        break
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
ans = 10**9

for i in range(N-K+1):
    if X[i] >= 0:
        ans = min(ans, X[K+i-1])
    elif X[K+i-1] <= 0:
        ans = min(ans, -X[i])
    else:
        ans = min(ans, 2*X[K+i-1]-X[i], X[K+i-1]-2*X[i])
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = sorted(list(map(int, input().split())))
cnt = []

for i in range(N - K + 1):
    left = X[i]
    right = X[i+K-1]
    cnt.append(min(abs(right)+abs(left-right), abs(left) + abs(right - left)))
print(min(cnt))

Submission status: Accepted

Solution code:
from bisect import bisect_left

n, k = list(map(int, input().split()))
x = list(map(int, input().split()))

pos = bisect_left(x, 0)
if pos < len(x) and x[pos] == 0:
    k -= 1
else:
    x.insert(pos, 0)

l = pos
r = pos+k

if r >= len(x):
    diff = r-len(x) + 1
    l -= diff
    r -= diff

ans = min(abs(x[l]), x[r])*2 + max(abs(x[l]), x[r])

while r >= pos:
    if l < 0:
        break

    dist = min(abs(x[l]), x[r])*2 + max(abs(x[l]), x[r])
    if dist < ans:
        ans = dist

    l -= 1
    r -= 1

print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
X=list(map(int,input().split()))
for i in range(N):
    if X[i]<0:
        continue
    elif X[i]==0:
        K-=1
        if i<K:
            mX=[0]+[-x for x in X[:i]][::-1]
        else:
            mX=[0]+[-x for x in X[i-K:i]][::-1]
        pX=[0]+X[i+1:i+1+K]
        break
    else:
        if i<K:
            mX=[0]+[-x for x in X[:i]][::-1]
        else:
            mX=[0]+[-x for x in X[i-K:i]][::-1]
        pX=[0]+X[i:i+K]
        break
else:
    mX=[0]+[-x for x in X[::-1]]
    pX=[0]
ans=10**9
l=K-(len(pX)-1)
n=len(mX)
for i in range(len(pX)-1,-1,-1):
    if l<n:
        ans=min(ans,pX[i]+mX[l]*2,pX[i]*2+mX[l])
    else:
        break
    l+=1
print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
X=list(map(int,input().split()))
p=True
for i in range(N):
    if X[i]<0:
        continue
    elif X[i]==0:
        K-=1
        if i<K:
            mX=[0]+[-x for x in X[:i]][::-1]
        else:
            mX=[0]+[-x for x in X[i-K:i]][::-1]
        pX=[0]+X[i+1:i+1+K]
        p=False
        break
    else:
        if i<K:
            mX=[0]+[-x for x in X[:i]][::-1]
        else:
            mX=[0]+[-x for x in X[i-K:i]][::-1]
        pX=[0]+X[i:i+K]
        p=False
        break
if p:
    mX=[0]+[-x for x in X[::-1]]
    pX=[0]
ans=10**9
l=K-(len(pX)-1)
n=len(mX)
for i in range(len(pX)-1,-1,-1):
    if l<n:
        ans=min(ans,pX[i]+mX[l]*2,pX[i]*2+mX[l])
    else:
        break
    l+=1
print(ans)

Submission status: Accepted

Solution code:
import sys
import bisect


def input():
    return sys.stdin.readline().rstrip()


def main():
    N, K = map(int, input().split())
    X = list(map(int, input().split()))
    S = []
    ans = 10 ** 9 + 7

    start = bisect.bisect(X, 0)

    for i in range(min(start+1,K+1)):
        temp = 0
        if N - start < K-i:  #右にある個数が取るべき個数を超えたときはスキップ
            continue

        if i ==0:
            ans = min(X[start+K-1],ans)
            continue

        if i ==K:
            ans =min(-X[start-K],ans)
            continue
        # 左から
        temp += -X[start - i] * 2
        temp += X[start + K - i-1]
        ans = min(temp, ans)

        # 右から

        temp = X[start + K - i-1] * 2
        temp += -X[start - i]
        ans = min(temp, ans)





    print(ans)




if __name__ == "__main__":
    main()

Submission status: Accepted

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

ans = float("inf")
for i in range(n-k+1):
  l = abs(x[i]) + abs(x[i]-x[i+k-1])
  r = abs(x[n-1-i]) + (x[n-1-i]-x[n-k-i])
  ans = min(ans,l,r)
print(ans)

Submission status: Accepted

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

ans = float("inf")
for i in range(n-k+1):
  # 0の位置から移動し、i〜i+kまでのろうそくに火をつけた場合の移動時間について左右で確認し、最小を求める
  l = abs(x[i]) + abs(x[i]-x[i+k-1])
  r = abs(x[i+k-1]) + abs(x[i] - x[i+k-1])
  ans = min(ans, l, r)
print(ans)

Submission status: Accepted

Solution code:
def resolve():
    '''
    code here
    '''
    N, K = [int(item) for item in input().split()]
    xs = [int(item) for item in input().split()]
    
    min_lr = 10**9
    min_rl = 10**9

    if N != K:
        for i in range(N-K+1):
            min_lr = min(min_lr, abs(xs[i]) + abs(xs[i+K-1] - xs[i]))
            min_rl = min(min_rl, abs(xs[i+K-1]) + abs(xs[i+K-1] - xs[i]))

        print(min(min_lr, min_rl))
    elif N ==1:
        print(abs(xs[0]))
    else:
        print(min(abs(xs[0]) + abs(xs[N-1] - xs[0]), abs(xs[N-1]) + abs(xs[N-1] - xs[0])))

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
n,k=list(map(int,input().split()))
a=list(map(int,input().split()))
import sys
if min(a)>=0:
  print(a[k-1])
  sys.exit()
if max(a)<=0:
  print((-1)*a[n-k])
  sys.exit()
  
ans=0
b=[]
for i in range(n-k+1):
  b.append(a[i+k-1]-a[i])

ans=float("INF")
for i in range(n):
  #i-k+1の正負、i+k-1の正負により変わる
  if i-k+1>=0 and i+k-1<=n-1:
    ans=min(ans,abs(a[i])+min(b[i],b[i-k+1]))
  elif i-k+1<0 and i+k-1<=n-1:
    ans=min(ans,abs(a[i])+b[i])
  elif i-k+1>=0 and i+k-1>n-1:
    ans=min(ans,abs(a[i])+b[i-k+1])
  else:
    ans=ans
    
print(ans)

Submission status: Accepted

Solution code:
n,k= list(map(int,input().split()))
pos= list(map(int,input().split()))
ans = 10**13
for i in range(n-k+1):
    a1 = abs(pos[i]) + abs(pos[i] - pos[i+k-1])
    a2 = abs(pos[i+k-1]) + abs(pos[i] - pos[i+k-1])
    ans = min(ans, a1,a2)
print(ans)

Submission status: Accepted

Solution code:
import sys

# sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846

def read_str():      return sys.stdin.readline().strip()
def read_int():      return int(sys.stdin.readline().strip())
def read_ints():     return map(int, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def lcm(a: int, b: int) -> int: return (a * b) // math.gcd(a, b)

def Main():
    n, k = read_ints()
    x = read_int_list()
    ans = INF

    for i in range(n - k + 1):
        left = x[i]
        right = x[i + k - 1]
        if left < 0 and right > 0:
            ans = min(ans, min(abs(left), abs(right)) * 2 + max(abs(left), abs(right)))
        else:
            ans = min(ans, max(abs(left), abs(right)))
    
    print(ans)
    
if __name__ == '__main__':
    Main()

Submission status: Accepted

Solution code:
import sys;          from decimal import Decimal
import math;         from numba import njit, i8, u1, b1
import bisect;       from itertools import combinations, product
import numpy as np;  from collections import Counter, deque, defaultdict

# sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846

def read_str():      return sys.stdin.readline().strip()
def read_int():      return int(sys.stdin.readline().strip())
def read_ints():     return map(int, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def lcm(a: int, b: int) -> int: return (a * b) // math.gcd(a, b)

def Main():
    n, k = read_ints()
    x = read_int_list()
    ans = INF

    for i in range(n - k + 1):
        left = x[i]
        right = x[i + k - 1]
        if left < 0 and right > 0:
            ans = min(ans, min(abs(left), abs(right)) * 2 + max(abs(left), abs(right)))
        else:
            ans = min(ans, max(abs(left), abs(right)))
    
    print(ans)
    
if __name__ == '__main__':
    Main()

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
*X,=map(int,input().split())
i=0
ans=[]
while i+K-1<N:
    a,b=X[i],X[i+K-1]
    if b<0:
        ans.append(abs(a))
    elif a>0:
        ans.append(b)
    else:
        a=abs(a)
        ans.append(a+b+min(a,b))
    i+=1
print(min(ans))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
*X,=map(int,input().split())
A=[]
B=[]
for x in X:
    if x>=0:
        A.append(x)
    else:
        B.append(abs(x))
B.sort()
i=min(K,len(A))
j=K-i
ans=[]
while i>=0 and j<=len(B):
    if i==0:
        ans.append(B[j-1])
    elif j==0:
        ans.append(A[i-1])
    else:
        a,b=A[i-1],B[j-1]
        ans.append(a+b+min(a,b))
    i-=1
    j+=1
print(min(ans))

Submission status: Accepted

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

res= 10**10

for i in range(n-k+1):
    st = al[i]
    en = al[i+k-1]
    if st *en <0:
        temp = min(abs(st),abs(en))*2+max(abs(st),abs(en))
    else:
        temp = max(abs(st),abs(en))
    res = min(temp,res)

print(res)

Submission status: Accepted

Solution code:
import sys
n,k=map(int,input().split())
x=list(map(int,input().split()))
left=[]
right=[]
origin=0
for u in x:
  if u<0:
    left.append(abs(u))
  elif u==0:
    origin+=1
  else:
    right.append(u)
left.sort()
k-=origin
if k==0:
  print(0)
  sys.exit()
r=len(right)
l=len(left)
ans=float('inf')
if k<=r:
  ans=right[k-1]
if k<=l:
  ans=min(ans,left[k-1])
for i in range(k-1):
  if i<r and k-i-2<l:
    y=right[i]+left[k-i-2]+min(right[i],left[k-i-2])
    ans=min(ans,y)
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
x=list(map(int,input().split()))
a=[x[i] for i in range(n) if x[i]<0]
b=[x[i] for i in range(n) if x[i]>=0]
na=len(a)
nb=len(b)
if 0 in x:
    k-=1
    b=[x[i] for i in range(n) if x[i]>0]
    nb=nb-1

if k==0:
    print(0)
    exit()
ans=10**10
if na>=k:
    ans=-a[-k]

if nb>=k:
    ans=min(ans,b[k-1])

if nb==0:
    print(-a[-k])
    exit()

if na==0:
    print(b[k-1])
    exit()

for i in range(1,nb+1):
    m=k-i
    if m>na or m<0:
        continue
    elif 0<m<=na:
        ans=min(ans,min(b[i-1]-2*a[-m],2*b[i-1]-a[-m]))
    elif m==0:
        ans=min(ans,b[k-1])
print(ans if k!=0 else 0)

Submission status: Accepted

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

lis = sorted(list(map(int, input().split())))

ans = []
for i in range(n-k+1):
    a = lis[i]
    b = lis[i+k-1]
    ans.append(min(abs(a)+abs(b-a),abs(b)+abs(a-b)))

print(min(ans))

Submission status: Accepted

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

ans = []
for i in range(N-K+1):
    if x[i] < 0 and x[i+K-1] > 0:
        ans += abs(x[i]) + abs(x[i+K-1]) + min(abs(x[i]),abs(x[i+K-1])),
    elif x[i] < 0:
        ans += -x[i],
    else:
        ans += x[i+K-1],
print(min(ans))

Submission status: Accepted

Solution code:
def main():
  N, K = [int(n) for n in input().split(" ")]
  X = [int(x) for x in input().split(" ")]
  X.sort()
  
  minus = []
  plus = []
  for i in range(len(X)):
    if X[i] < 0:
      minus.append(-X[i])
    else:
      plus += X[i:]
      break

  minus.reverse()

  T = []
  
  if len(plus) >= K:
    T.append(plus[K - 1])
  if len(minus) >= K:
    T.append(minus[K - 1])
  for i in range(K):
    if i < len(plus) and 0 <= K - i - 2 < len(minus):
      T.append(2 * plus[i] + minus[K - i - 2])
      T.append(2 * minus[K - i - 2] + plus[i])
    if i < len(minus) and 0 <= K - i - 2 < len(plus):
      T.append(2 * minus[i] + plus[K - i - 2])
      T.append(2 * plus[K - i - 2] + minus[i])
  
  print(min(T))

main()

Submission status: Accepted

Solution code:
# 連続するK本のろうそくに火をつけるので、最小となる組を全探索する
N, K = map(int, input().split())
X = list(map(int, input().split()))

ans = float("INF")
for i in range(N - K + 1):
    lr = abs(X[i]) + abs(X[i] - X[i + K - 1])
    rl = abs(X[i + K - 1]) + abs(X[i + K - 1] - X[i])
    ans = min(ans, min([lr, rl]))

print(ans)

Submission status: Accepted

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

s = 10**9

for i in range(n-k+1):
    if x[i] * x[i+k-1] >= 0:
        t = max(abs(x[i]), abs(x[i+k-1]))
    else:
        t = abs(x[i]) + abs(x[i+k-1]) + min(abs(x[i]), abs(x[i+k-1]))

    s = min(s, t)

print(s)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
x = list(map(int,input().split()))
li = []
for i in range(n-k+1):
    li += [x[k-1+i]-x[i]+min(abs(x[k-1+i]),abs(x[i]))]
print(min(li))

Submission status: Accepted

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

x1 = [i for i in x0 if i >= 0]
x2 = list(reversed([i for i in x0 if i < 0]))
count0 = len(x1)
count1 = len(x2)
ans = float('inf')

if count1 == 0:
    print(x1[k-1])
elif count0 == 0:
    print(-x2[k-1])
else:
    if 0 in x1:
        x1.remove(0)
        k -= 1
        count0 -= 1
    for i in range(min(count0, k)):
        if count1 >= k-i-1:
            ans = min(ans, x1[i]*2-x2[k-i-2])
    for i in range(min(count1, k)):
        if count0 >= k-i-1:
            ans = min(ans, -x2[i]*2+x1[k-i-2])
    print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
l = list(map(int,input().split()))
ans = 10**13
for i in range(n-k+1):
    left = l[i]
    right = l[k+i-1]
    if right <= 0:
        time = abs(left)
    elif 0 <= left:
        time = abs(right)
    else:
        time = min(abs(left),abs(right))*2 + max(abs(left),abs(right))
    ans = min(ans,time)
print(ans)

Submission status: Accepted

Solution code:
import sys
n,k = map(int,input().split())
x_ls = list(map(int, input().split()))
x_ls.sort()
if x_ls[0] >= 0:
    print(x_ls[k-1])
    sys.exit()
elif x_ls[-1] <= 0:
    x_ls.sort(reverse=True)
    print(abs(x_ls[k-1]))
    sys.exit()
l = 0
r = k - 1
ans = float('inf')
while r < n:
    cost_1 = 2*abs(x_ls[l]) + abs(x_ls[r])
    cost_2 = abs(x_ls[l]) + 2*abs(x_ls[r])
    cost = min(cost_1,cost_2)
    ans = min(cost, ans)
    r += 1
    l += 1
print(ans)

Submission status: Accepted

Solution code:
import math
N, K = map(int, input().split())
x = list(map(int, input().split()))
for i in range(N):
  if x[i] == 0:
    p, m = i, i+1
    break
  elif x[i] > 0:
    p, m = i, i
    break
    
if (x[0]<0) and (x[-1]>0):
  pls = x[p:]
  mns = x[:m]
  ans = math.inf

  for i in range(len(pls)):
    if i < K-1:
      if pls[0] == 0:
        n = K - i
      else:
        n = K - i - 1
      if len(mns) >= n:
        tmp = 2*abs(mns[-n]) + pls[i]
        ans = min(ans, tmp)
    if i == K-1:
      ans = min(ans, pls[i])
      break
    
  for i in range(len(mns)):
    m = len(mns)-i
    if m < K:
      if pls[0] == 0:
        n = K - m
      else:
        n = K - m - 1
      if len(pls) > n:
        tmp = 2*pls[n] + abs(mns[-m])
        ans = min(ans, tmp)
    if m == K:
      ans = min(ans, abs(mns[i]))
    
elif x[0] >= 0:
  ans = x[K-1]
  
else:
  ans = abs(x[-K])
  
print(ans)

Submission status: Accepted

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

neg_to_pos = n
for i in range(n):
    if x[i] > 0:
        neg_to_pos = i
        break

res = 10 ** 14
for i in range(n - k + 1):
    l = min(x[i], 0)
    r = max(0, x[i + k - 1])
    if i <= neg_to_pos and neg_to_pos - 1 <= i + k - 1:
        tmp = min(-2 * l + r, -l + 2 * r)
        res = min(res, tmp) 
print(res)

Submission status: Accepted

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

for i in range(n):
    if x[i] > 0:
        neg_num = i
        break
pos_num = n - neg_num

l = min(k, neg_num)
res = 10 ** 13
for i in range(l, -1, -1):
    r = k - i
    if r <= pos_num:
        l_val = min(0, x[neg_num - i])
        r_val = max(0, x[neg_num + k - i - 1])
        tmp = min( -l_val * 2 + r_val, -l_val + r_val * 2)
        res = min(tmp, res)
print(res)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = 10**10
for i in range(n-k+1):
    tmp = min(abs(a[k+i-1] - a[i]) + abs(a[i]), abs(a[k+i-1] - a[i]) + abs(a[k+i-1]))
    if ans > tmp:
        ans = tmp
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
import math
#from itertools import product, accumulate, combinations, product
import bisect
import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal

INF = 1 << 50


def run():
    N, K = map(int, sysread().split())
    X = list(map(int, sysread().split()))

    best_time = INF
    for i in range(0, N-K+1):
        left = X[i]
        right =  X[i+K-1]
        if left<=0:
            if right <= 0:
                best_time = min(best_time, abs(left))
            else:
                best_time = min(abs(left) + right + min(abs(left), right), best_time)
        else:
            best_time = min(best_time, right)
            break

    print(best_time)


if __name__ == "__main__":
    run()

Submission status: Accepted

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

ans = []
for i in range(N - K + 1):
    left = i
    right = left + K - 1
    if x[left] < 0 and x[right] >= 0:
        q = min(abs(x[left]) * 2 + x[right], x[right] * 2 + abs(x[left]))
        ans.append(q)
        continue
    elif x[right] < 0:
        q = abs(x[left])
        ans.append(q)
        continue
    elif x[left] > 0:
        q = abs(x[right])
        ans.append(q)
        continue
if len(ans) == 0:
    print(0)
    exit()

print(min(ans))

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


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

    X.sort()
    ans = float("inf")
    for l in range(N - K + 1):
        r = l + K - 1
        l2r = abs(X[l]) + abs(X[l] - X[r])
        r2l = abs(X[r]) + abs(X[r] - X[l])
        ans = min(ans, l2r, r2l)

    print(ans)


if __name__ == "__main__":
    main()