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

N, K = LI()
X = LI()
if 0 in X:
    X.remove(0)
    K -= 1

if K == 0:
    print(0)
    exit()
# 累積和を使う
distances = []
mid = bisect.bisect_left(X, 0)
#  print(mid)
#  if mid == 0:
#      # 正の数しかない
#      distances = [0]
#      for x in X:
#          distances.append(distances[-1] + x)
#      distances = distances[1:]
#  else:
#      # 負の数あり
#      negs = [0]
#      for x in X[:mid]:
#          # 負の数を足して逆にする
#          negs.append(negs[-1] + x)
#      negs = negs[::-1][:-1]
#      posi = [0]
#      for x in X[mid:]:
#          posi.append(posi[-1] + x)
#      posi = posi[1:]
#      distances = negs + posi

#  from itertools import accumulate
#  distances = list(accumulate(X))
for x in X:
    if x < 0:
        distances.append(-x)
    else:
        distances.append(x)
#  print('dist', distances)

#左端から右にずれていく。
results = []
for start in range(N):
    end = start + K
    if end > N: break
    #  print('start, end', start, end)
    #  if end >= len(X): break
    if start < mid < end:
        # 飛び越える場合
        results.append(min(distances[start], distances[end-1]) * 2 + max(distances[start], distances[end-1]))
    elif start >= mid:
        # 全部右側
        results.append(distances[end-1])
    else:
        results.append(distances[start])

#  print(results)
print(min(results))

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):
    l = x[i]
    r = x[i+K-1]
    sec1 = abs(l) + abs(r-l)
    sec2 = abs(r) + abs(l-r)
    ans = min(ans, sec1, sec2)
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
N , K = map( int , input().split())
lst = list(map(int, input().split()))
ans = 10 ** 9

for i in range(N - K + 1):
    # 全て正（先頭がゼロ以上）であれば、最大の正数（一番右の数）が最小時間となる
    if lst[i] >= 0:
        ans = min(ans, lst[i + K -1])
    # 全て負（一番右がゼロ以下）であれば、最小の整数（一番左の数）が最小時間となる
    elif lst[i + K -1] <= 0:
        ans = min(ans, abs(lst[i]))
    # 上記以外は、正負混在のケース    
    else:
        #  一番右の方が大きいとき
        if abs(lst[i]) < lst[i + K -1]:
            # 負の方向から折り返してくる方が最小なので
            ans = min(ans , abs(lst[i]) * 2 + lst[i + K -1])
        else:
            # 正の方向から折り返してくる方が最小なので
            ans = min(ans , abs(lst[i]) + lst[i + K -1] * 2)

print(ans)

Submission status: Accepted

Solution code:
n,k=list(map(int,input().split(" ")))
x=list(map(int,input().split(" ")))
x_=[]
for i in range(n-k+1):
    if x[i+k-1]<=0:
        x_.append(-x[i])
    elif x[i+k-1]>=0 and x[i]<=0:
        x_.append(2*min(abs(x[i+k-1]),abs(x[i]))+max(abs(x[i+k-1]),abs(x[i])))
    else:
        x_.append(x[i+k-1])
print(min(x_))

Submission status: Accepted

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

ans = 1e9
for l, r in zip(X, X[K-1:]):
  ans = min(ans, r-l+min(abs(l),abs(r)))
print(ans)

Submission status: Accepted

Solution code:
N, K = [int(x) for x in input().split()]
X = [int(x) for x in input().split()]

def main():
    k = K
    l = len(X) 

    i = 0

    ans = float('inf')
    end = l - k
    while i <= end:
        first = X[i]
        last = X[i + k - 1]
        node_abs = [abs(first), abs(last)]
        if first * last >= 0:
            curr = max(node_abs)
        else:
            curr = max(node_abs) + (min(node_abs) * 2)
        ans = min(ans, curr)
        i += 1
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
MAX = 300000001

N, K = map(int, input().split())
xn = [int(i) for i in input().split()]


def main():
    if 0 < xn[0]:
        print(xn[K - 1])
        return

    if xn[N - 1] < 0:
        print(abs(xn[N - K]))
        return

    ans = MAX

    for i in range(N - K + 1):
        if xn[i + K - 1] < 0 and i + K <= N - 1 and 0 < xn[i + K]:
            ans = min(ans, abs(xn[i]))

        elif 0 < xn[i]:
            if 0 != i:
                if xn[i - 1] < 0:
                    ans = min(ans, abs(xn[i + K - 1]))
                else:
                    break

        elif 0 <= xn[i + K - 1]:
            ans = min(ans,
                      2 * abs(xn[i]) + abs(xn[i + K - 1]),
                      abs(xn[i]) + 2 * abs(xn[i + K - 1]))

    print(ans)
    return


main()

Submission status: Accepted

Solution code:
MAX = 300000001

N, K = map(int, input().split())
xn = [int(i) for i in input().split()]


def main():
    if 0 < xn[0]:
        print(xn[K - 1])
        return

    if xn[N - 1] < 0:
        print(abs(xn[N - K]))
        return

    ans = MAX

    for i in range(N - K + 1):
        if xn[i + K - 1] < 0 and i + K <= N - 1 and 0 < xn[i + K]:
            ans = min(ans, abs(xn[i]))

        elif 0 < xn[i] and 0 != i and xn[i - 1] < 0:
            ans = min(ans, abs(xn[i + K - 1]))

        elif 0 <= xn[i + K - 1]:
            ans = min(ans,
                      2 * abs(xn[i]) + abs(xn[i + K - 1]),
                      abs(xn[i]) + 2 * abs(xn[i + K - 1]))

    print(ans)
    return


main()

Submission status: Accepted

Solution code:
MAX = 300000001

N, K = map(int, input().split())
xn = [int(i) for i in input().split()]


def main():
    if 0 < xn[0]:
        print(xn[K - 1])
        return

    if xn[N - 1] < 0:
        print(abs(xn[N - K]))
        return

    ans = MAX

    for i in range(N - K + 1):
        ans = min(ans,
                  2 * abs(xn[i]) + abs(xn[i + K - 1]),
                  abs(xn[i]) + 2 * abs(xn[i + K - 1]))

    print(ans)
    return


main()

Submission status: Accepted

Solution code:
MAX = 300000001

N, K = map(int, input().split())
xn = [int(i) for i in input().split()]


def main():
    if 0 <= xn[0]:
        print(xn[K - 1])
        return

    if xn[N - 1] < 0:
        print(abs(xn[N - K]))
        return

    ans = MAX

    for i in range(N - K + 1):
        ans = min(ans,
                  2 * abs(xn[i]) + abs(xn[i + K - 1]),
                  abs(xn[i]) + 2 * abs(xn[i + K - 1]))

    print(ans)
    return


main()

Submission status: Accepted

Solution code:
MAX = 300000001

N, K = map(int, input().split())
xn = [int(i) for i in input().split()]


def main():
    if 0 <= xn[0]:
        print(xn[K - 1])
        return

    if xn[N - 1] < 0:
        print(abs(xn[N - K]))
        return

    ans = MAX

    for i in range(N - K + 1):
        if xn[i + K - 1] < 0 and i + K <= N - 1 and 0 < xn[i + K]:
            ans = min(ans, abs(xn[i]))

        elif 0 <= xn[i + K - 1]:
            ans = min(ans,
                      2 * abs(xn[i]) + abs(xn[i + K - 1]),
                      abs(xn[i]) + 2 * abs(xn[i + K - 1]))

    print(ans)
    return


main()

Submission status: Accepted

Solution code:
MAX = 300000001

N, K = map(int, input().split())
xn = [int(i) for i in input().split()]


def main():
    if 0 <= xn[0]:
        print(xn[K - 1])
        return

    if xn[N - 1] < 0:
        print(abs(xn[N - K]))
        return

    ans = MAX

    for i in range(N):
        if N - 1 < i + K - 1:
            break

        if xn[i] < 0:
            if xn[i + K - 1] < 0 and i + K <= N - 1 and 0 < xn[i + K]:
                ans = min(ans, abs(xn[i]))

            elif 0 <= xn[i + K - 1]:
                ans = min(ans,
                          2 * abs(xn[i]) + abs(xn[i + K - 1]),
                          abs(xn[i]) + 2 * abs(xn[i + K - 1]))

        elif 0 == xn[i]:
            ans = min(ans, xn[i + K - 1])

    print(ans)
    return


main()

Submission status: Accepted

Solution code:
MAX = 300000001

N, K = map(int, input().split())
xn = [int(i) for i in input().split()]


def main():
    if 0 <= xn[0]:
        print(xn[K - 1])
        return

    if xn[N - 1] < 0:
        print(abs(xn[N - K]))
        return

    ans = MAX

    for i in range(N):
        if N - 1 < i + K - 1:
            break

        if xn[i] < 0:
            if xn[i + K - 1] < 0 and i + K <= N - 1 and 0 < xn[i + K]:
                ans = min(ans, abs(xn[i]))

            elif 0 <= xn[i + K - 1]:
                ans = min(ans,
                          2 * abs(xn[i]) + abs(xn[i + K - 1]),
                          abs(xn[i]) + 2 * abs(xn[i + K - 1]))

        elif 0 == xn[i]:
            ans = min(ans, xn[i + K - 1])

        elif 0 != i and xn[i - 1] < 0:
            ans = min(ans, xn[i + K - 1])

    print(ans)
    return


main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
xs = list(map(int, input().split()))
ans = 1e20
for i in range(N-K+1):
    xl = xs[i]
    xr = xs[i+K-1]
    ltor = abs(xl) + abs(xl-xr)
    rtol = abs(xr) + abs(xl-xr)
    t = min(ltor, rtol)
    if t < ans:
        ans = t
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
sec = 3 * 10**8
for i in range(n - k + 1):
    if x[i] * x[i + k - 1] < 0:
        sec = min(sec, abs(x[i]*2) + x[i + k - 1], abs(x[i]) + x[i + k - 1] * 2)
    else:
        sec = min(sec, max(abs(x[i]), abs(x[i + k - 1])))
print(sec)

Submission status: Accepted

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

x = list(map(int,input().split()))
res = 10**16
for i in range(len(x)-k+1):
    res = min(res,abs(x[i])+abs(x[i+k-1]-x[i]),abs(x[i+k-1])+abs(x[i+k-1]-x[i]))
print(res)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
x = list(map(int, input().split()))
d = 2 * (x[-1] - x[0])
for i in range(N-K+1):
    d = min(d, abs(x[i]) + abs(x[i + K - 1] - x[i]),abs(x[i + K -1]) + abs(x[i + K - 1] - x[i]))
print(d)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
x = list(map(int, input().split()))
dist = 2 * (x[-1] - x[0])
for i in range(N):
    if i + K -1 >= N:
        break
    dist = min(dist, abs(x[i]) + abs(x[i + K - 1] - x[i]),abs(x[i + K -1]) + abs(x[i + K - 1] - x[i]))
print(dist)

Submission status: Accepted

Solution code:
def candles(N: int, K: int, X: int)->int:
    min_d = float('inf')
    for i in range(N-K+1):
        xl, xr = X[i], X[i+K-1]
        min_d = min(min_d, abs(xl) + abs(xr - xl), abs(xr) + abs(xr - xl))

    return min_d


if __name__ == "__main__":
    N, K = map(int, input().split())
    X = [int(s) for s in input().split()]
    ans = candles(N, K, X)
    print(ans)

Submission status: Accepted

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

res = 1e9+7
for l, r in zip(x,x[K-1:]):
  tmp = r - l
  if(abs(l) < abs(r)):
    tmp += abs(l)
  else:
    tmp += abs(r)
  if(res > tmp):
    res = tmp
print(res)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
x=list(map(int,input().split()))
n=N-K+1
left=[0]*n
for i in range(n):left[i]=abs(x[i])+abs(x[i]-x[i+K-1])
x=x[::-1]
right=[0]*n
for i in range(n):right[i]=abs(x[i])+abs(x[i]-x[i+K-1])
print(min(min(left),min(right)))

Submission status: Accepted

Solution code:
import bisect
N, K = map(int, input().split())
x = list(map(int, input().split()))
t = 2 * (x[-1] - x[0])
i = bisect.bisect_right(x, 0)
for j in range(0, N):
    if N <= j + K -1 :
        break
    if (j - (i - 0.1)) * (j + K- 1 - (i - 0.1)) >= 0:
        t = min(t, max(abs(x[j]), abs(x[j+K-1])))
    else:
        t = min(t, abs(2 * x[j]) + x[j+K-1])
        t = min(t, abs(x[j]) + 2 * x[j+K-1])
print(t)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
x=list(map(int,input().split()))
left=[0]*(N-K+1)
right=[0]*(N-K+1)
for i in range(len(left)):left[i]=abs(x[i])+abs(x[i+K-1]-x[i])
x=x[::-1]
for i in range(len(right)):right[i]=abs(x[i])+abs(x[i+K-1]-x[i])
print(min(min(left),min(right)))

Submission status: Accepted

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

ans = min(b - a + min(abs(a), abs(b)) for a, b in zip(x, x[K-1:]))

print(ans)

Submission status: Accepted

Solution code:
import numpy as np

N,K=list(map(int,input().split()))
x=list(map(int,input().split()))
t_min=10**9+7
for i in range(N-K+1):
    t=x[i+K-1]-x[i]+min(np.abs(x[i]),np.abs(x[i+K-1]))
    if t<t_min:
        t_min=t
print(t_min)

Submission status: Accepted

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

ans = 10**18
for i in range(n-k+1):
    x_s, x_e = x[i], x[i+k-1]
    if x_e <= 0:
        ans_tmp = -x_s
    elif x_s < 0 and 0 < x_e:
        ans_tmp = min(x_e-2*x_s, 2*x_e-x_s)
    else:
        ans_tmp = x_e
    ans = min(ans, ans_tmp)
print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
x = list(map(int,input().split()))
result = 1e10
for i in range(N-K+1):
  result = min(result, abs(x[i])+x[i+K-1]-x[i])
  result = min(result, abs(x[i+K-1])+x[i+K-1]-x[i])
print(result)

Submission status: Accepted

Solution code:
# https://qiita.com/_-_-_-_-_/items/34f933adc7be875e61d0
# abcde	s=input()	s='abcde'
# abcde	s=list(input())	s=['a', 'b', 'c', 'd', 'e']
# 5(1つだけ)	a=int(input())	a=5
# 1 2	| x,y = map(int,input().split())   |	x=1,y=2
# 1 2 3 4 5 ... n 　	li = input().split()	li=['1','2','3',...,'n']
# 1 2 3 4 5 ... n 　	li = inpl()	li=[1,2,3,4,5,...,n]
# FFFTFTTFF 　	li = input().split('T')	li=['FFF', 'F', '', 'FF']

# INPUT
# 3
# hoge
# foo
# bar
# ANSWER
# n=int(input())
# string_list=[input() for i in range(n)]

import math
import numpy as np
import copy
from collections import defaultdict, Counter
from itertools import product
from bisect import bisect_left, bisect_right
def inpl(): return list(map(int, input().split()))


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

all_time = []
for ind in range(N-K+1):
    l = x[ind]
    r = x[ind+K-1]
    all_time.append(min(abs(l)+abs(r-l), abs(r)+abs(l-r)))

print(min(all_time))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
lst1=input()
lst2=lst1.split(" ")
lst=[]
for i in lst2:
    lst.append(int(i))

minr=[]
minl=[]

for i in range(n-k+1):
    l=i
    r=i+k-1
    minr.append(abs(lst[r])+abs(lst[r]-lst[l]))
    minl.append(abs(lst[l])+abs(lst[r]-lst[l]))

minr.sort()
minl.sort()

m=min(minr[0],minl[0])
print(m)

Submission status: Accepted

Solution code:
import math
import sys

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

mn = sys.maxsize

for i in range(n-k+1):
	mn = min(mn, abs(x[i]-x[i+k-1])+abs(x[i+k-1]))
for i in range(n-1, k-2, -1):
	mn = min(mn, abs(x[i]-x[i-k+1])+abs(x[i-k+1]))

print(mn)

Submission status: Accepted

Solution code:
import bisect

def solve():
    N, K = map(int, input().split())
    x = list(map(int, input().split()))
    if K == 0:
        return 0
    if 0 in x:
        x.remove(0)
        K -= 1
    if K == 0:
        return 0

    x.sort()

    mid = bisect.bisect_left(x, 0)
    p = [0]
    m = [0]
    for i in range(mid, N):
        p.append(x[i])
    for i in range(mid - 1, -1, -1):
        m.append(-x[i])
    pcnt = len(p) - 1
    mcnt = len(m) - 1
    inf = 1 << 60
    min_sc = inf
    for i in range(K+1):
        if mcnt < K - i:
            continue
        if pcnt < i:
            continue
        if m[K - i] > p[i]:
            sc = m[K - i] + p[i] * 2
        else:
            sc = m[K - i] * 2 + p[i]
        min_sc = min(min_sc, sc)
    return min_sc

ans = solve()
print(ans)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc107/tasks/arc101_a

import itertools
import collections
import bisect

def main():
    # big value
    INF = int(1e15)

    N, K = map(int, input().split())
    X = [-INF] + list(map(int, input().split())) + [INF]
    pos = bisect.bisect(X, 0) # 0より大きい中で最小の要素のインデックス
    # print(pos)

    right_num = N - pos + 1
    left_num = pos - 1

    ans = INF
    if right_num >= K:  # 右側からだけ取れるなら
        ans = min(ans, abs(X[pos + K - 1]))
    # print(ans)

    for i in range(1, K):  # 左側からいくつ取るか
        if i > left_num:  # 左側に取れるだけ数がないなら continue
            continue
        if K - i > right_num:  # 右側に取れるだけ数がないなら continue
            continue

        left_distance = abs(X[pos - i])
        right_distance = abs(X[pos + K - i - 1])
        # min(一番左までの距離 x 往復 + 一番右までの距離, 一番右までの距離 x 往復 + 一番左までの距離)
        ans = min(ans, left_distance * 2 + right_distance, right_distance * 2 + left_distance)

    if left_num >= K:  # 左側からだけ取れるなら
        ans = min(ans, abs(X[pos - K]))
    # print(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 = 10 ** 9
for i in range(n-k+1):
  a = abs(x[i+k-1] - x[i])
  ans = min(ans,min(abs(x[i+k-1])+a,abs(x[i])+a))
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import bisect

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

if 0 in X:
  K=K-1
ans=[]
Right=[]
Left=[]
  
for x in X:
  if x>0:
    Right.append(x)
  else:
    Left.append(abs(x))

Left.append(0)
Left.sort()
Right=[0]+Right
    
for i in range(K+1):
  if i<=len(Right)-1 and K-i<=len(Left)-1:
    ans.append(min(Right[i],Left[K-i])*2+max(Right[i],Left[K-i]))

if K==0:
  ans.append(0)

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):
  xl=X[i]
  xr=X[i+K-1]
  ans.append(min(abs(xl)+abs(xr-xl),abs(xr)+abs(xl-xr)))

print(min(ans))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 2019/3/1
Solved on 2019/3/  WA
@author: shinjisu
"""


# ABC 107 C Candles
def getInt(): return int(input())


def getIntList(): return [int(x) for x in input().split()]


def zeros(n): return [0]*n


def getIntLines(n): return [int(input()) for i in range(n)]


def getIntMat(n):
    mat = []
    for i in range(n):
        mat.append(getIntList())
    return mat


def zeros2(n, m): return [zeros(m)]*n


ALPHABET = [chr(i+ord('a')) for i in range(26)]
DIGIT = [chr(i+ord('0')) for i in range(10)]
N1097 = 10**9 + 7
INF = 10**12


def dmp(x, cmt=''):
    global debug
    if debug:
        if cmt != '':
            print(cmt, ':  ', end='')
        print(x)
    return x


def probC_WA():
    N, K = getIntList()
    X = getIntList()
    dmp((N, K, X))
    X = [-INF] + X + [INF]
    dmp(X)
    for i in range(N+2):
        if X[i] >= 0:
            break
    zeroIdx = i
    dmp(zeroIdx, 'zeroIdx')
    fromIdx = max(1, zeroIdx-K+1)
    dmp(fromIdx, 'fromIdx')
    # X[fromIdx] = 0 if X[fromIdx] == -INF else X[fromIdx]
    minTime = INF
    # for i in range(fromIdx, N+2-fromIdx-K+1):
    # for i in range(fromIdx, N+2-K+1):
    for i in range(fromIdx, N+2-K):
        if X[i] >= 0:
            moveTime = X[i+K-1]
        elif X[i+K-1] <= 0:
            moveTime = abs(X[i])
        else:
            plDist = X[i+K-1]
            mnDist = abs(X[i])
            moveTime = min(plDist, mnDist)*2 + max(plDist, mnDist)
        dmp((i, minTime, moveTime), 'moveTime in loop')
        minTime = min(minTime, moveTime)
    return minTime


def probC():
    N, K = getIntList()
    X = getIntList()
    dmp((N, K, X))
    # X = [-INF] + X + [INF]
    # dmp(X)
    # for i in range(N+2):
    for i in range(N):
        if X[i] >= 0:
            break
    zeroIdx = i
    dmp(zeroIdx, 'zeroIdx')
    fromIdx = max(0, zeroIdx-K+1)
    dmp(fromIdx, 'fromIdx')
    # X[fromIdx] = 0 if X[fromIdx] == -INF else X[fromIdx]
    minTime = INF
    # for i in range(fromIdx, N+2-fromIdx-K+1):
    # for i in range(fromIdx, N+2-K+1):
    for i in range(fromIdx, N-K+1):
        if X[i] >= 0:
            moveTime = X[i+K-1]
        elif X[i+K-1] <= 0:
            moveTime = abs(X[i])
        else:
            plDist = X[i+K-1]
            mnDist = abs(X[i])
            moveTime = min(plDist, mnDist)*2 + max(plDist, mnDist)
        dmp((i, minTime, moveTime), 'moveTime in loop')
        minTime = min(minTime, moveTime)
    return minTime


debug = False  # True False
ans = probC()
print(ans)
#for row in ans:
#    print(row)

Submission status: Accepted

Solution code:
def solve(string):
    n, k, *x = map(int, string.split())
    x = sorted(x)
    diff = [
        _x1 - _x0 + min(abs(_x0), abs(_x1)) if _x0 <= 0 <= _x1 else max(abs(_x0), abs(_x1))
        for _x0, _x1 in zip(x, x[k - 1:])
    ]
    return str(min(diff))


if __name__ == '__main__':
    print(solve('\n'.join([input(), input()])))

Submission status: Accepted

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

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

time = []

for i in range(N-K+1):
  t = min(abs(lst[i]) + abs(lst[i] - lst[i + K - 1]),abs(lst[i + K -1]) + abs(lst[i] - lst[i + K -1]))
  time.append(t)
                           
print(min(time))

Submission status: Accepted

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


def solve(N: int, K: int, x: "List[int]"):
    def search(N, window_size, x):
        costs = []
        for i in range(N-window_size+1):
            right_end = x[i+window_size-1]
            left_end = x[i]
            dist = abs(right_end-left_end)
            costs.append(min(abs(right_end)+dist, abs(left_end)+dist))
        return min(costs)
    print(search(N, K, x))
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    x = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(N, K, x)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import math
import sys

import math
import sys


n,k = map(int, sys.stdin.readline().rstrip().split())
xs = list(map(int, sys.stdin.readline().rstrip().split()))

mn = sys.maxsize
for i in range(n-k+1):
  mn = min(mn, abs(xs[i]-xs[i+k-1])+abs(xs[i+k-1]))

for i in range(n-1,k-2,-1):
  mn = min(mn, abs(xs[i]-xs[i-k+1])+abs(xs[i-k+1]))
  
print(mn)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
mintime = 10**20
for i in range(n-k+1):
    left = x[i]
    right = x[i+k-1]
    abss = (abs(left), abs(right))
    if left * right >= 0:
        mintime = min(mintime, max(abss))
    else:
        mintime = min(mintime, min(abss) * 2 + max(abss))
print(mintime)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
X = [int(i) for i in input().split()]

min_cost = float('inf')

for i in range(N-K+1):
    l = X[i]
    r = X[i+K-1]
    tmp_l = abs(l) + abs(r-l)
    tmp_r = abs(r) + abs(l-r)
    tmp = min(tmp_l,tmp_r)

    if min_cost > tmp:
        min_cost = tmp

print(min_cost)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
locations = list(map(int,input().split()))
tmp = 10 ** 18

for left in range(n-k+1):
    right = left + k - 1
    if locations[left] * locations[right] > 0:
        answer = max(abs(locations[left]),abs(locations[right]))
    else:
        answer1 = abs(locations[left]) * 2 + locations[right]
        answer2 = locations[right]* 2 + abs(locations[left])
        answer = min(answer1,answer2)
    tmp = min(tmp,answer)
    
print(tmp)

Submission status: Accepted

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

l = 0
r = 0

for li in reversed(range(0, n)):
    if x[li] < 0:
        l += 1
        if l == k:
            break

for ri in range(0, n):
    if x[ri] > 0:
        r += 1
        if r == k:
            break
    
c = 10**9

def t(a, b):
    if a * b < 0:
        return min(abs(a) * 2 + abs(b), abs(a) + abs(b) * 2)
    else:
        return max(abs(a), abs(b))

for i in range(li, ri + 2 - k):
    ci = t(x[i], x[i + k - 1])
    
    if ci < c:
        c = ci
            
print(c)

Submission status: Accepted

Solution code:
import sys
import math
import collections
import itertools
import array
import inspect

# Set max recursion limit
sys.setrecursionlimit(1000000)


# Debug output
def chkprint(*args):
    names = {
        id(v): k
        for k, v in inspect.currentframe().f_back.f_locals.items()
    }
    print(', '.join(
        names.get(id(arg), '???') + ' = ' + repr(arg) for arg in args))


# Binary converter
def to_bin(x):
    return bin(x)[2:]


def li_input():
    return [int(_) for _ in sys.stdin.readline().split()]


def gcd(n, m):
    if n % m == 0:
        return m
    else:
        return gcd(m, n % m)


def gcd_list(L):
    v = L[0]

    for i in range(1, len(L)):
        v = gcd(v, L[i])

    return v


def lcm(n, m):
    return (n * m) // gcd(n, m)


def lcm_list(L):
    v = L[0]

    for i in range(1, len(L)):
        v = lcm(v, L[i])

    return v


# Width First Search (+ Distance)
def wfs_d(D, N, K):
    """
    D: 隣接行列(距離付き)
    N: ノード数
    K: 始点ノード
    """

    dfk = [-1] * (N + 1)
    dfk[K] = 0

    cps = [(K, 0)]
    r = [False] * (N + 1)
    r[K] = True
    while len(cps) != 0:
        n_cps = []
        for cp, cd in cps:
            for i, dfcp in enumerate(D[cp]):
                if dfcp != -1 and not r[i]:
                    dfk[i] = cd + dfcp
                    n_cps.append((i, cd + dfcp))
                    r[i] = True

        cps = n_cps[:]

    return dfk


# Depth First Search (+Distance)
def dfs_d(v, pre, dist):
    """
    v:  現在のノード
    pre: １つ前のノード
    dist: 現在の距離

    以下は別途用意する
    D: 隣接リスト(行列ではない)
    D_dfs_d: dfs_d関数で用いる，始点ノードから見た距離リスト
    """

    global D
    global D_dfs_d

    D_dfs_d[v] = dist

    for next_v, d in D[v]:
        if next_v != pre:
            dfs_d(next_v, v, dist + d)

    return


def sigma(N):
    ans = 0
    for i in range(1, N + 1):
        ans += i
    return ans


def comb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2, r + 1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p - 1, r, p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def bisearch(L, target):
    low = 0
    high = len(L) - 1
    
    while low <= high:
        mid = (low + high) // 2
        guess = L[mid]
        if guess == target:
            return True
        elif guess < target:
            low = mid + 1
        elif guess > target:
            high = mid - 1
    if guess != target:
        return False

# --------------------------------------------

dp = None


def main():
    N, K = li_input()
    A = li_input()
    D = []

    for i in range(N - K + 1):
        l,r = A[i],A[i+K-1]
        D.append(min(abs(l) + abs(r - l), abs(r) + abs(r - l)))

    print(min(D))


main()