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:
n,k=map(int,input().split())
x = list(map(int,input().split()))
sd=100000000
if n==k:
  sd=min(abs(x[0])+abs(x[0]-x[k-1]),abs(x[k-1])+abs(x[0]-x[k-1]))
else:
  for i in range(n-k+1):
    d=min(abs(x[i])+abs(x[i]-x[i+k-1]),abs(x[i+k-1])+abs(x[i]-x[i+k-1]))
    if sd>d:
      sd=d
print(sd)

Submission status: Accepted

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

ret = float('inf')
for i in range(0, N - K + 1):
    ret = min(ret,
              abs(x[K + i - 1] - x[i]) + min(abs(x[i]), abs(x[K + i - 1]))
              )
print(ret)

Submission status: Accepted

Solution code:
n,k = list(map(int,input().split()))
x = list(map(int,input().split()))
result = -2 # 初期値！

for i in range(n-k+1):
    xl,xr = x[i],x[i+k-1]
    if result == -2 or min(abs(xl),abs(xr)) + xr - xl < result: # 初期値なら最適なのに更新、resultよりちいさかったら同じく更新する！。
        result = min(abs(xl),abs(xr)) + xr - xl

print(result)

Submission status: Accepted

Solution code:

import sys


def main():
    N, K = list(map(int, input().split()))
    values = list(map(int, input().split()))
    res = sys.maxsize - 1
    for i in range(N - K + 1):
        start = values[i]
        end = values[i + K - 1]

        if start * end > 0:
            cur = (max(abs(start), abs(end)))
            res = min(res, cur)
        else:
            cur = (end - start + min(abs(start), abs(end)))
            res = min(res, cur)
    print(res)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

ans = -1

for i in range(N - K + 1):
    l, r = i, i + K - 1
    xl = x[l]
    xr = x[r]
    tmp = min(abs(xl),abs(xr)) + xr - xl
    if ans == -1 or tmp < ans:
        ans = tmp
        
print(ans)

Submission status: Accepted

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

X = list(map(int, input().split()))

pos_start_index = 0

if X[0] > 0:
  pos_start_index = 0
elif X[N-1] < 0:
  pos_start_index = N

for n in range(N-1):
  if X[n] == 0:
    pos_start_index = n
    break
  elif X[n] < 0 and X[n+1] > 0:
    pos_start_index = n+1
    break


neg_sum_list = []

for j, idx in enumerate(range(pos_start_index-1, -1, -1)):
  neg_sum_list.append(-X[idx])

pos_sum_list = []

for j, idx in enumerate(range(pos_start_index, N)):
  pos_sum_list.append(X[idx])


res = []

for j, neg_sum in enumerate(neg_sum_list):
  neg_count = j+1
  pos_count = K - neg_count

  if neg_count == K:
    res.append(neg_sum)
    break

  if pos_count <= len(pos_sum_list):
    pos_sum = pos_sum_list[pos_count-1]
    res.append(2*neg_sum + pos_sum)

for j, pos_sum in enumerate(pos_sum_list):
  pos_count = j+1

  neg_count = K - pos_count

  if pos_count == K:
    res.append(pos_sum)
    break

  if neg_count <= len(neg_sum_list):
    neg_sum = neg_sum_list[neg_count-1]
    res.append(2*pos_sum + neg_sum)

print(min(res))

Submission status: Accepted

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

Submission status: Accepted

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

plus = [0]
minus = []
zeroExist = 0

for i in range(n):
    if x[i] > 0:
        plus.append(x[i])
    elif x[i] == 0:
        zeroExist = 1
    else:
        minus.append(-x[i])
minus.append(0)
minus = list(reversed(minus))

if zeroExist == 1:
    k -= 1

cost = 10**9
for i in range(k + 1):
    if i < len(plus) and k - i < len(minus):
        # print("i:{} k-i:{}".format(i, k-i))
        if i == 0 or i == k:
            cost = min(cost, plus[i] + minus[k - i])
        else:
            cost = min(cost, plus[i] + minus[k - i]
                       + min(plus[i], minus[k - i]))
            # print("{}:{}".format(i, cost))
print(cost)

Submission status: Accepted

Solution code:

def getIntList():
    return list(map(int, input().split()))    

N, K = getIntList()

zx = getIntList()
res = 10000000000
for i in range(N-K+1):
    a = zx[i]
    b = zx[i+K-1]
    if  a*b <0:
        a = abs(a)
        b = abs(b)
        t = min(a,b)*2 + max(a,b)
    else:
        a = abs(a)
        b = abs(b)
        t = max(a,b)
    res = min(res,t)
print(res)

Submission status: Accepted

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

min_path=4*(10**8)
for i in range(N-K+1):
	if x[i]<0 and x[i+K-1]<0:
		if min_path>-x[i]:
			min_path=-x[i]
	if x[i]<0 and x[i+K-1]>=0:
		if -x[i]>x[i+K-1]:
			if min_path > -x[i]+2*x[i+K-1]:
				min_path=-x[i]+2*x[i+K-1]
		else:
			if min_path > -x[i]*2 + x[i+K-1]:
				min_path=-x[i]*2 + x[i+K-1]
	if x[i]>=0 and x[i+K-1]>=0:
		if min_path>x[i+K-1]:
			min_path=x[i+K-1]

			
print min_path

Submission status: Accepted

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

dis_list = []

for i in range(N-K+1):
    dis_list.append(x[i+K-1] -x[i] + min(abs(x[i]),abs(x[i+K-1])))
print(min(dis_list))

Submission status: Accepted

Solution code:
import sys 

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

ans = sys.maxsize 
for i in range(N-K+1):
  ans = min(ans, 
          abs(x[i])+abs(x[i+K-1]-x[i]), 
          abs(x[i+K-1])+abs(x[i]-x[i+K-1]))

print(ans)

Submission status: Accepted

Solution code:
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))

n , k =I()
a = I()
m = 10**10
for i in range(n - k + 1):
	m = min(m , a[i+k-1] - a[i] + min(abs(a[i]) , abs(a[i+k-1])))
print(m)

Submission status: Accepted

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

res = 10 ** 10
l = 0
r = k-1
while r <= n-1:
    res = min(res,min(abs(x[l]),abs(x[r]))+(x[r]-x[l]))
    l+=1
    r+=1
print(res)

Submission status: Accepted

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

ans = int(1e18)
for i in range(N-(K-1)):
    a = x[i]
    b = x[i+K-1]
    ans = min(ans, min(abs(a), abs(b)) + abs(b - a))

print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
xxx = list(map(int, input().split()))
print(min(min(abs(l), abs(r)) + r - l for l, r in zip(xxx, xxx[k - 1:])))

Submission status: Accepted

Solution code:
n,k = list(map(int,input().split()))
x = list(map(int,input().split()))
ans = float('inf')
i = 0
while i+k-1<n:
    ans = min(ans,-x[i]+x[i+k-1]+abs(x[i]),-x[i]+x[i+k-1]+abs(x[i+k-1]))
    i += 1
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):
    tmp1=abs(x[i])+abs(x[i]-x[i+K-1])
    tmp2=abs(x[i+K-1])+abs(x[i]-x[i+K-1])
    ans=min([ans,tmp1,tmp2])
print(ans)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,k = LI()
    a = LI()
    bi = bisect.bisect_left(a, 0)
    r = inf
    if bi >= k:
        r = abs(a[bi-k])
    if bi+k-1 < n and r > a[bi+k-1]:
        r = a[bi+k-1]
    for i in range(1, n):
        if 0 > bi - i or bi + k - i - 1 >= n or bi + k - i - 1 < bi:
            continue
        t = -a[bi-i]
        u = a[bi+k-i-1]
        s = t + u + min(t,u)
        if r > s:
            r = s
    return r



print(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, abs(X[i] - X[i+K-1]) + abs(X[i]))
    ans = min(ans, abs(X[i] - X[i+K-1]) + abs(X[i+K-1]))

print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
i = 0
while i < n and x[i] < 0:
    i += 1
jl = i - 1
cl = []
cr = []
for l in range(k):
    if jl - l < 0:break
    cl.append(-x[jl - l])
for l in range(k):
    if i + l >= n:break
    cr.append(x[i + l])
la = 10**18
lb = 10**18
for l in range(len(cl)):
    c = k - l - 2
    if c >= len(cr):continue
    if c < 0:
        la = min(la, cl[l])
    else:
        la = min(la, cl[l] + cr[c] * 2)
for l in range(len(cr)):
    c = k - l - 2
    if c >= len(cl):continue
    if c < 0:
        lb = min(lb, cr[l])
    else:
        lb = min(lb, cr[l] + cl[c] * 2)
print(min(la, lb))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
X=[int(i) for i in input().split()]
ans=10**18
for i in range(N-K+1):
    ans=min(ans,abs(X[i])+abs(X[i+K-1]-X[i]))
    ans=min(ans,abs(X[i+K-1])+abs(X[i+K-1]-X[i]))
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = [int(x) for x in input().split()]
ans = 10 ** 9
for i in range(N - K + 1):
  ans = min(X[i + K - 1] - X[i] + min(abs(X[i]), abs(X[i + K - 1])), ans)
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import bisect


def solve():
    n, k = map(int, input().split())
    al = [int(i) for i in input().split()]

    ans = sum(abs(i) for i in al)
    flag0 = 0 in al
    if flag0:
        k -= 1
        n -= 1
        if k == 0:
            print(0)
            return
        al.remove(0)
    nc = bisect.bisect_left(al, 0)
    for i in range(n):
        if i < 0 or i + k - 1 >= n:
            break
        if al[i] < 0 and al[i + k - 1] < 0:
            t1 = abs(al[i])
        else:
            t1 = min(abs(al[i]) * 2 + abs(al[i + k - 1]),
                     abs(al[i]) + abs(al[i + k - 1]) * 2)
        if al[i] > 0 and al[i + k - 1] > 0:
            t2 = abs(al[i + k - 1])
        else:
            t2 = min(abs(al[i]) * 2 + abs(al[i + k - 1]),
                     abs(al[i]) + abs(al[i + k - 1]) * 2)
        t = min(t1, t2)
        ans = min(ans, t)
    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n, k = map(int, input().split())
x = list(map(int, input().split()))
ans = float('inf')
for l in range(0, n - k + 1):
    r = l + k - 1
    if x[r] <= 0:
        ans = min(ans, - x[l])
    elif 0 <= x[l]:
        ans = min(ans, x[r])
    else:
        assert x[l] <= 0 <= x[r]
        ans = min(ans, + x[r] - 2 * x[l])
        ans = min(ans, - x[l] + 2 * x[r])
print(ans)

Submission status: Accepted

Solution code:
import bisect

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

if 0 in x:
	a=bisect.bisect_left(x,0)
else:
	bisect.insort(x,0)
	a=bisect.bisect_left(x,0)
	n+=1
	k+=1

ans=float('inf')
for i in range(max(0,a+k-n),min(k,a+1)):
	ans=min(ans,-2*x[a-i]+x[a-i+k-1])
for i in range(max(0,k-a-1),min(k,n-a)):
	ans=min(ans,2*x[a+i]-x[a+i-k+1])
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import bisect


def solve():
    n, k = map(int, input().split())
    al = [int(i) for i in input().split()]

    ans = sum(abs(i) for i in al)
    flag0 = 0 in al
    if flag0:
        k -= 1
        n -= 1
        if k == 0:
            print(0)
            return
        al.remove(0)
    nc = bisect.bisect_left(al, 0)
    for i in range(n):
        if i < 0 or i + k - 1 >= n:
            break
        if al[i] < 0 and al[i + k - 1] < 0:
            t1 = abs(al[i])
        else:
            t1 = min(abs(al[i]) * 2 + abs(al[i + k - 1]),
                     abs(al[i]) + abs(al[i + k - 1]) * 2)
        if al[i] > 0 and al[i + k - 1] > 0:
            t2 = abs(al[i + k - 1])
        else:
            t2 = min(abs(al[i]) * 2 + abs(al[i + k - 1]),
                     abs(al[i]) + abs(al[i + k - 1]) * 2)
        t = min(t1, t2)
        ans = min(ans, t)
    for i in range(n - 1, -1, -1):
        if i - k + 1 < 0 or i >= n:
            break
        if al[i] < 0 and al[i - k + 1] < 0:
            t1 = abs(al[i - k + 1])
        else:
            t1 = min(abs(al[i - k + 1]) * 2 + abs(al[i]),
                     abs(al[i - k + 1]) + abs(al[i]) * 2)
        if al[i] > 0 and al[i - k + 1] > 0:
            t1 = abs(al[i])
        else:
            t2 = min(abs(al[i - k + 1]) * 2 + abs(al[i]),
                     abs(al[i - k + 1]) + abs(al[i]) * 2)
        t = min(t1, t2)
        ans = min(ans, t)
    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import bisect

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

zero_ind=bisect.bisect_left(x,0)
"""
print("max",0,k-zero_ind-1)
print("min",k,n-zero_ind)
print("max",1,k-n+zero_ind-1)
print("min",k,zero_ind+2)
"""
v,w=10**9,10**9
if(n-zero_ind >= k):v=abs(x[zero_ind+k-1])
if(zero_ind >= k):w=abs(x[zero_ind-k])

y=[10**9]
z=[10**9]

if(zero_ind != 0 and zero_ind != n):
    for i in range(max(0,k-zero_ind-1),min(k,n-zero_ind)):
        if(zero_ind+i<0 or zero_ind+i>=n or zero_ind-(k-i)+1<0 or zero_ind-(k-i)+1>=n):continue
        y.append(abs(x[zero_ind+i])+abs(x[zero_ind+i]-x[zero_ind-(k-i)+1]))
    for i in range(max(1,k-n+zero_ind-1),min(k,zero_ind+2)):
        if(zero_ind-i<0 or zero_ind-i>=n or zero_ind+(k-i)-1<0 or zero_ind+(k-i)-1>=n):continue
        z.append(abs(x[zero_ind-i])+abs(x[zero_ind-i]-x[zero_ind+(k-i)-1]))
    """
    y=[abs(x[zero_ind+i])+abs(x[zero_ind+i]-x[zero_ind-(k-i)+1]) for i in range(max(0,k-zero_ind-1),min(k,n-zero_ind))]
    z=[abs(x[zero_ind-i])+abs(x[zero_ind-i]-x[zero_ind+(k-i)-1]) for i in range(max(1,k-n+zero_ind-1),min(k,zero_ind+2))]
    """

"""
for i in range(k):
    print(abs(x[zero_ind+i]))
    print(x[zero_ind-(k-i)+1])

for i in range(1,k):
    print(abs(x[zero_ind-i]))
    print(x[zero_ind+(k-i)-1])
"""
print(min([v,w]+y+z))
"""
print(y)
print(z)
"""

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# 
import math
import sys
import itertools
import numpy as np

# なんこか入力
n,k = map(int, input().split())

# 空白区切りの数列をリストに代入
x = [int(i) for i in input().split()]
c = 0
for a in range(0,n):
    if x[a]==0:
        b=a
        c=1
        break
    if x[a]>0:
        b=a
        break

answer = 1000000000

if x[0] >= 0:
    answer = x[k-1]
elif x[n-1] <= 0:
    answer = -x[n-k]        
else:
    if n-b+c > k:
        answer = min(answer, x[b+k-1-c])
    if b+c > k:
        answer = min(answer, -x[b-k+c])
    for i in range(0,n):
        if i<b:
            if (b-i) < (k-c) and (i+k-1)<n:
                l=-x[i]+(x[i+k-1]-x[i])
                answer = min(answer,l)
        elif i==b:
            continue
        else:
            if (i-b) < (k-c+1) and i > (k-2):
                l=x[i] + (x[i]-x[i-k+1])
                answer = min(answer,l)




print(answer)

Submission status: Accepted

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

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

LL = []
RR = []

for a in A:
    if a<0:
        LL.append(a*(-1))
    else:
        RR.append(a)

Llen = len(LL)
min_ans = sum(LL)+sum(RR)
for i in range(N-K+1):
    ans = 0
    #左完結
    if i+K<=Llen: ans = LL[i]
    #右完結
    elif i>=Llen: ans = RR[K-1]
    #それ以外
    else:
        #print(i)
        lr = [LL[i],RR[i+K-Llen-1]]
        ans = max(lr)+min(lr)*2
            
    #print(ans)
    if ans<min_ans:min_ans = ans
        
print(min_ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
a=list(map(int, input().split()))
b=list(map(abs, a))
i=b.index(min(b))
c=list(filter(lambda x: x>=0, a))
e=sorted(c)
d=list(map(abs, filter(lambda x: x<0, a)))
f=sorted(d)

lp=len(c)
lm=len(d)
s=[]
if 0 in a:
    K -=1

if K==0:
    print(0)
elif lp==0:
    print(f[K-1])
elif lm==0:
    print(e[K-1])
elif K==N:
    print(min(2*e[lp-1]+f[lm-1],2*f[lm-1]+e[lp-1]))
else:
    for i in range(lp):
        if K-i<=lm:
            if i==K:
                u=e[i-1]
            else:
                u=2*e[i-1]+f[K-i-1]
            s.append(u)
    for t in range(lm):
        if K-t<=lp:
            if t==K:
                q=f[t-1]
            else:
                q=2*f[t-1]+e[K-t-1]
            s.append(q)

    print(min(s))

Submission status: Accepted

Solution code:
a,b = map(int,input().split())
m = 0
c = list(map(int,input().split()))
for i in range(len(c)-b+1):
    if c[i] * c[i+b-1] < 0:
        if i == 0:
            m = abs(c[i]) + c[i+b-1] +abs(min(abs(c[i]),c[i+b-1]))
        else:
            m = min(m,abs(c[i]) + c[i+b-1] +abs(min(abs(c[i]),c[i+b-1])))
    else:
        if i == 0:
            m = max(abs(c[i]),abs(c[i+b-1]))
        else:
            m = min(m,max(abs(c[i]),abs(c[i+b-1])))

print(m)

Submission status: Accepted

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

if((0 in x) == True):
    state = x.index(0)
    k -= 1
else:
    x.append(0)
    x = sorted(x)
    state = x.index(0)

ans = int(1e10)
for left in range(k+1):
    right = k - left
    if(((state - left) >= 0) and ((state + right) <= (len(x) - 1))):
        if(right > 0): tmp = -2 * x[state-left]
        else: tmp = -1 * x[state-left]
        tmp += x[state+right]
        if(ans > tmp): ans = tmp

        tmp = -1 * x[state-left]
        if(left > 0): tmp += 2 * x[state+right]
        else: tmp += x[state+right]
        if(ans > tmp): ans = tmp

print(ans)

Submission status: Accepted

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

Sum_list = []
for i in range (N-K+1):
    Sum_list.append(Rosoku_list[i+K-1]-Rosoku_list[i])
    
for index , current_sum in enumerate(Sum_list):
    
    if Rosoku_list[index]*Rosoku_list[index+K-1] >  0:
        if Rosoku_list[index] > 0 :
            Sum_list[index] += abs(Rosoku_list[index])
        elif Rosoku_list[index] < 0 :
            Sum_list[index] += abs(Rosoku_list[index + K -1])
            
    elif Rosoku_list[index]*Rosoku_list[index+K-1] <  0:
        if abs(Rosoku_list[index]) <= abs(Rosoku_list[index+K-1]):
            Sum_list[index] +=abs(Rosoku_list[index])
        else:
            Sum_list[index] +=abs(Rosoku_list[index+K-1])
        
    #elif Rosoku_list[index]*Rosoku_list[index+K-1] ==  0:
        
print(min(Sum_list))

Submission status: Accepted

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


inv_idx = n

for i, x in enumerate(xs):
    if x >= 0:
        inv_idx = i
        break

ps = []
for i, x in enumerate(xs[inv_idx:]):
    ps.append(x)

ns = []
for i, x in enumerate(reversed(xs[:inv_idx])):
    ns.append(-x)

if inv_idx == 0:
    print(ps[k-1])
    exit(0)
elif inv_idx == n:
    print(ns[k-1])
    exit(0)

n_seach_end = max(0, min(len(ns), k - 1))
p_seach_end = max(0, min(len(ps), k - 1))

n_seach_start = max(0, k - len(ps) - 1)
p_seach_start = max(0, k - len(ns) - 1)

ans = 10 ** 13

for i in range(n_seach_start, n_seach_end):
    ans = min(ans, 2 * ns[i] + ps[k - 2 - i])

for i in range(p_seach_start, p_seach_end):
    ans = min(ans, 2 * ps[i] + ns[k - 2 - i])

if len(ns) >= k:
    ans = min(ans, ns[k - 1])

if len(ps) >= k:
    ans = min(ans, ps[k - 1])

print(ans)

Submission status: Accepted

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

def main():
	n, k = map(int, input().split())
	a = [int(i) for i in input().split()]
	ans = 10**9
	for i in range(k-1, n):
		if a[i-k+1] * a[i] < 0:
			ans = min(ans, a[i-k+1]*(-2) + a[i], a[i-k+1]*(-1)+2*a[i])
		else:
			ans = min(ans,max(abs(a[i-k+1]) , abs(a[i])))
	print(ans)
	return

main()

Submission status: Accepted

Solution code:
import numpy as np
import bisect

N, K = map(int, input().split())
x_np = np.array(list(map(int, input().split())))

idx0 = bisect.bisect_left(x_np, 0)
right_cost = x_np[idx0:]
right_cost = np.append(np.zeros(1), right_cost)


if idx0 > 0:
    left_cost = np.zeros(1)
    left_cost = np.append(left_cost, -x_np[idx0-1::-1])

    res = 10**16
    iter_s = max(0, K - (N-idx0))
    iter_e = min(K, idx0)

    if iter_s == 0:
        res = min(res, right_cost[K])
    if iter_e == K:
        res = min(res, left_cost[K])

    for i in range(max(1, iter_s), min(K, iter_e+1)):
        res = min(res, left_cost[i]*2 + right_cost[K-i], left_cost[i] + right_cost[K-i]*2)

    print(int(res))
else:
    print(int(right_cost[K]))

Submission status: Accepted

Solution code:
from bisect import bisect_left
n,k = (int(i) for i in input().split())
x = [int(i) for i in input().split()]
a,ans = bisect_left(x,0),float("inf")
if 0 in x and k==1: ans = 0
elif 0 in x: x,k = x[:a]+x[a+1:],k-1 
for i in range(k+1):
	if -1<a-k+i<n and -1<a+i-1<n:
		if i==0: ans = min(-x[a-k+i],ans)
		elif i==k: ans = min(x[a+i-1],ans)
		else: ans = min(-2*x[a-k+i]+x[a+i-1],2*x[a+i-1]-x[a-k+i],ans)
print(ans)

Submission status: Accepted

Solution code:
N, K = [int(x) for x in input().split()]
X = [int(x) for x in input().split()]
minvalue = None
for i in range(0, N-K+1):
	j = i+K-1
	if i == j:
		k = abs(X[i])
	elif X[i]*X[j]>=0:
		k = max(abs(X[i]), abs(X[j]))
	else:
		k = min(abs(X[i])*2+X[j], abs(X[i])+X[j]*2)
	if minvalue is None:
		minvalue = k
	else:
		minvalue = min(minvalue, k)
print(minvalue)

Submission status: Accepted

Solution code:
def main(N, K, xs):

    if xs[0] >= 0:
        return xs[K-1]
    if xs[-1] <= 0:
        return abs(xs[-1 * K])

    for i, x in enumerate(xs):
        if x == 0:
            xs.pop(i)
            if K == 1:
                return 0
            K = K-1
            N = N-1
        if x > 0:
            zi = i
            break

    result = None

    if zi - K >= 0:
        result = -1 * xs[zi - K]
    if zi + K - 1 <= N-1:
        if result == None:
            result = xs[zi + K - 1]
        result = min(result, xs[zi + K - 1])

    for i in range(K-1):
        if zi - K + i + 1 < 0:
            continue
        if zi - 1 + i + 1 > N-1:
            continue
        l = abs(xs[zi-K+i+1])
        r = abs(xs[zi-1+i+1])
        if result == None:
            result = 2 * min(l, r) + max(l, r)
        else:
            if result > 2 * min(l, r) + max(l, r):
                result = 2 * min(l, r) + max(l, r)
    return result

N, K = [int(i) for i in input().split(' ')]
xs = [int(i) for i in input().split(' ')]

print(main(N, K, xs))

Submission status: Accepted

Solution code:
from bisect import bisect_left

n, k = map(int, input().split())
x = list(map(int, input().split()))
pos = bisect_left(x, 0)
#print(bisect_left(x, 0))


if n == 1:
	print(abs(x[0]))
elif x[0] >= 0:
	print(x[k - 1])
elif x[-1] <= 0:
	print(-x[-k])
else:
	ans = float("inf")
	if pos + k <= n:
		ans = x[pos + k - 1]
	if x[pos] == 0:
		if pos - k + 1 >= 0:
			ans = min(ans, -x[pos - k + 1])
	else:
		if pos - k >= 0:
			ans = min(ans, -x[pos - k])
	for i in range(max(0, k - pos - 1), min(k - 1, n - pos)):
		#print(i)
		right = x[pos + i]
		left = -x[pos - (k - i - 1)]
		#print(right, left)
		ans = min(ans, 2 * right + left, 2 * left + right)

	print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect
N, K = map( int, input().split())
X = list( map( int, input().split()))
I = bisect(X, -1)
Xmin = X[:I]
Xmin = [ -x for x in Xmin[::-1]]
Xplu = X[I:]
H = [10**9]*(10**5)
Xmin += H
Xplu += H
ans = 10**9
for i in range( min(I, K)):
    if i == K-1:
        ans = min(ans, Xmin[i])
    else:
        ans = min(ans, Xmin[i]*2 + Xplu[K-i-2])
for i in range( min(N-I, K)):
    if i == K-1:
        ans = min(ans, Xplu[i])
    else:
        ans = min(ans, Xplu[i]*2 + Xmin[K-i-2])
print(ans)

Submission status: Accepted

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

ans = 10 ** 10
for  i,x  in enumerate(xs):
    if N == 1:
        ans = abs(x)
    if i +  K  > N and i > 0:
        break
    num = abs(xs[ i + K - 1 ] - xs[i]) + abs(xs[i])
    num1 = abs(xs[ i + K - 1 ] - xs[i]) + abs(xs[i + K -1])
    ans = min([num,num1,ans])
print(ans)

Submission status: Accepted

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

x = list(map(int, input().split(" ")))

zero = None

min_length = 1000000000

for i in range(0, n - k + 1):
    lx = x[i]
    rx = x[i + k - 1]

    if((lx <= 0 and rx <= 0) or (lx >= 0 and rx >= 0)):
        abslx = abs(lx)
        absrx = abs(rx)
        min_length = min(min_length, max(abslx, absrx))
    else:
        abslx = abs(lx)
        absrx = abs(rx)
        xlength = min(abslx, absrx) * 2 + max(abslx, absrx)
        min_length = min(min_length, xlength)
        
print(min_length)

Submission status: Accepted

Solution code:
def inpl(): return list(map(int, input().split()))
N, K = inpl()
x = inpl()
candidates = []
for i in range(N-K+1):#mini return
    if x[i]*x[i+K-1]<0:#またぐ
        if abs(x[i])<abs(x[i+K-1]):#mini return
            candidates.append(abs(x[i])+abs(x[i+K-1]-x[i]))
        else:#maxi return
            candidates.append(abs(x[i+K-1])+abs(x[i+K-1]-x[i]))
    
    else:#またがない
        candidates.append(max(abs(x[i]),abs(x[i+K-1])))
        

print(min(candidates))

Submission status: Accepted

Solution code:
# C
N, K = map(int, input().split())
x_list = list(map(int, input().split()))

zero_cnt = 0
posi_ind = N
nega_ind = -1

# minus
for i in range(N):
    if x_list[i] == 0:
        zero_cnt = 1
        nega_ind = i-1
    elif x_list[i] > 0:
        posi_ind = i
        if zero_cnt == 0:
            nega_ind = i-1
        break
if zero_cnt == 1:
    K -= 1

if x_list[N-1] < 0:
    nega_ind = N-1
    
nega_seq = list(reversed(x_list[:(nega_ind+1)]))
posi_seq = x_list[posi_ind:]

res = 10**13
if K == 0:
    res = 0
else:
    for i in range(1, min(len(posi_seq)+1, K)):
        if K-i-1 >= len(nega_seq) or K-i-1 < 0:
            continue
        p = posi_seq[i-1]
        n = -nega_seq[K-i-1]
        r = min(2*p+n, 2*n+p)
        res = min(res, r)
    if len(posi_seq) >= K:
        r = posi_seq[K-1]
        res = min(res, r)
    if len(nega_seq) >= K:
        r = -nega_seq[K-1]
        res = min(res, r)
print(res)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys


def main():
    n, k = [int(v) for v in sys.stdin.readline().rstrip().split(' ')]
    x = [int(v) for v in sys.stdin.readline().rstrip().split(' ')]

    c = 0
    while c<n and x[c] < 0:
        c += 1


    def getCost(l, r):
        if l<c and c<=r-1:
            return min(-x[l]*2+x[r-1], x[r-1]*2-x[l])
        elif c>r-1:
            return -x[l]
        else:
            return x[r-1]
    cost = getCost(0, k)

    for i in range(1,n-k+1):
        cost = min(cost, getCost(i, i+k))
    
    print(cost)
        

      
if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

num1 = bisect_left(xs, 0)
num2 = N - num1

d1s = [0] + [-x for x in xs[:num1]][::-1]
d2s = [0] + xs[num1:]

ans = float('inf')
for i in range(max(0, K - num2), min(num1, K) + 1):
    d1, d2 = d1s[i], d2s[K - i]
    ans = min(ans, d1 + d2 + min(d1, d2))

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = [int(x) for x in input().split()]
ans = 10 ** 9
if K == 1:
  ans = min([abs(x) for x in X])
elif K == N:
  ans = X[N - 1] - X[0] + min(abs(X[0]), abs(X[N - 1]))
for i in range(N - K + 1):
  ans = min(X[i + K - 1] - X[i] + min(abs(X[i]), abs(X[i + K - 1])), ans)
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from bisect import bisect, bisect_left
def inpl(): return list(map(int, input().split()))
N, K = inpl()
X = inpl()
ans = 10**9

r0 = bisect_left(X, 0)

for i in range(N):
    #print(r0+i, r0-K+i+1)
    if (0 <= r0+i < N) and (0 <= r0-K+i+1 < N):
        if X[r0+i] < 0 or X[r0-K+i+1] > 0:
            continue
        #print(2*X[r0+i] - X[r0-K+i+1])
        #print(X[r0+i] - 2*X[r0-K+i+1])
        ans = min(ans, 2*X[r0+i] - X[r0-K+i+1])
        ans = min(ans, X[r0+i] - 2*X[r0-K+i+1])

if r0+K-1 < N:
    ans = min(X[r0+K-1], ans)
if r0-K >= 0:
    ans = min(-X[r0-K], ans)

print(ans)

Submission status: Accepted

Solution code:
import sys
N,K=map(int,input().split())
X=[int(i) for i in input().split()]
A=[]
B=[]
for x in X:
    if x<0:
        A.append(x)
    else:
        B.append(x)
ans=10**18
a=len(A)
b=len(B)
if a==0:
    print(B[K-1])
    sys.exit()
if b==0:
    print(abs(A[-K]))
    sys.exit()
for i in range(max(1,K-b),a+1):
    if i>=K:
        ans=min(ans,abs(A[-i]))
        continue
    ans = min(ans,2*abs(A[-i])+B[K-i-1])
for i in range(max(0,K-a-1),b):
    if i>=K-1:
        ans=min(ans,abs(B[i]))
        continue
    ans=min(ans,2*abs(B[i])+abs(A[-K+i+1]))
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
pl, mi = 0, 0
recp, recm = [], []
for i in range(n):
    if x[i] >= 0:
        pl += 1
        recp.append(x[i])
    else:
        mi += 1
        recm.append(x[i])

num = float("inf")
recm = recm[:: -1]
for i in range(pl + 1):
    if i == 0:
        if k <= mi:
            num = min(num, abs(recm[k - 1]))
        else:
            continue
    else:
        if k - i == 0:
            num = min(num, recp[k - 1])
        elif 0 < k - i <= mi:
            num = min(num, recp[i - 1] + 2 * abs(recm[k - i - 1]))
            num = min(num, 2 * recp[i - 1] + abs(recm[k - i - 1]))

print(num)

Submission status: Accepted

Solution code:
#!python
# -*- coding: utf-8 -*-


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

    p = [0]
    m = []

    for n in x:
        if n < 0:
            m.append(-n)
        if n == 0:
            K -= 1
        if n > 0:
            p.append(n)
    m.reverse()
    m = [0] + m
    if K == 0:
        print(0)
        return

    ANS = float('inf')
    for i in range(K + 1):
        p_i = i
        m_i = K - i
        if not 0 <= p_i < len(p):
            continue
        if not 0 <= m_i < len(m):
            continue

        ANS = min(ANS, p[p_i] * 2 + m[m_i])
        ANS = min(ANS, p[p_i] + m[m_i] * 2)

    print(ANS)






if __name__ == '__main__':
    main()