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: Runtime Error

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

left = []
right = []
for x in X:
    if x<0:
        left.append(abs(x))
    else:
        right.append(x)
left.reverse()

# from math import inf
ans = 10**18

#i=>right
for i in range(K+1):
    if right[0]==0:
        if i==0:
            continue;
    temp = 0
    if len(left)==0:
        temp = right[K-1]
    elif len(right)==0:
        temp = left[K-1]
    elif len(left)>=(K-i):
        if len(right)>=i:
            temp0 = left[K-i-1]
            temp1 = right[i-1]
            temp  = temp0+temp1 + min(temp0, temp1)
        else:
            temp0 = right[-1]
            temp1 = left[K-len(right)-1]
            temp  = temp0+temp1 + min(temp0, temp1)
    else:
        temp = left[-1] if len(left)!=0 else 0
        temp += right[K-len(left)-1]
    ans = min(ans, temp)

print(ans)

Submission status: Runtime Error

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

left = []
right = []
for x in X:
    if x<0:
        left.append(abs(x))
    else:
        right.append(x)
left.reverse()

from math import inf
ans = inf

#i=>right
for i in range(K+1):
    if right[0]==0:
        if i==0:
            continue;
    temp = 0
    if len(left)==0:
        temp = right[K-1]
    elif len(right)==0:
        temp = left[K-1]
    elif len(left)>=(K-i):
        if len(right)>=i:
            temp0 = left[K-i-1]
            temp1 = right[i-1]
            temp  = temp0+temp1 + min(temp0, temp1)
        else:
            temp0 = right[-1]
            temp1 = left[K-len(right)-1]
            temp  = temp0+temp1 + min(temp0, temp1)
    else:
        temp = left[-1] if len(left)!=0 else 0
        temp += right[K-len(left)-1]
    ans = min(ans, temp)

print(ans)

Submission status: Runtime Error

Solution code:
n,m=map(int,input().split())
l=list(map(int,input().split()))
l1=[]
for i in range(n-m+1):
  if l[i]>=0:
    l1.append(l[i+m]-l[i])
  elif l[i]<=0<=l[i+m]:
    l1.append(l[i+m]-l[i]+min(l[i],l[i+m]))
  else:
    l1.append(l[i+m]-l[i])
print(min(l1))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
li=list(map(int,input().split()))
q=[]
for i in range(k,n):
  if li[i-1]<=0:
    q.append(-li[i-k])
  elif li[i-k]>=0:
    q.append(li[i-1])
  else:
    q.append(li[i-1]-li[i-k]+min(li[i-1],abs(li[i-k])))
print(min(q))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
li=list(map(int,input().split()))
q=[]
for i in range(k,n):
  if li[i-1]<0:
    q.append(-li[i-k])
  elif li[i-k]>0:
    q.append(li[i-1])
  else:
    q.append(li[i-1]-li[i-k]+min(li[i-1],abs(li[i-k])))
print(min(q))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
li=list(map(int,input().split()))
q=[]
for i in range(k,n):
  if i<0 or i-k+1>0:
    q.append(li[i-1]-li[i-k])
  else:
    q.append(li[i-1]-li[i-k]+min(li[i-1],abs(li[i-k])))
print(min(q))

Submission status: Runtime Error

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

min_time = 2 * 10 ** 8
for i in range(N):
    print(i)
    if i + K > N:
        break
    if a[i] > 0:
        min_time = min(min_time, abs(a[i + K - 1]))
        break
    
    if a[i + K - 1] < 0:
        if i + K <= N and a[i + K] > 0:
            min_time = min(min_time, abs(a[i]))
        continue
        
    min_time = min(min_time, 2 * abs(a[i]) + abs(a[i + K - 1]), abs(a[i]) + 2 * abs(a[i + K - 1]))

print(min_time)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
X = list(map(int,input().split()))
from bisect import bisect_left as bl
zero = bl(X,0)
ans = 0

temp = []
for i in range(max(zero,k-1),min(zero+k,n)):
    
    if X[i-k+1] >= 0:
        temp.append(X[i])
    elif X[i] <= 0:
        temp.append(abs(X[i-k+1]))
    else:
        temp.append(min(abs(X[i]),abs(X[i-k+1]))*2+max(abs(X[i]),abs(X[i-k+1])))
print(min(temp))

Submission status: Runtime Error

Solution code:
import sys

n, k = [int(n) for n in input().split(" ")]
fire = [int(n) for n in input().split(" ")]

if (n == 1):
    print(k * fire[0])
    sys.exit()
elif (k == 0):
    print(0)
    sys.exit()

diff = [0] * len(fire)
zero = -1

for i in range(0, len(diff)):
    if (zero == -1 and fire[i + 1] * fire[i] <= 0):
        fire.insert(i + 1, 0)
        zero = i + 1

    diff[i] = fire[i + 1] - fire[i]

if (zero == -1):
    fire.append(0)
    zero = len(fire - 1)

for i in range(0, n - k):
    if (zero == 0 or diff[0] < diff[-1]):
        diff.pop()
        fire.pop()
    elif (diff[-1] > diff[0] or abs(fire[0]) > abs(fire[-1])):
        diff.pop(0)
        fire.pop(0)
        zero -= 1
    else:
        diff.pop()
        fire.pop()

if (zero != 0):
    a = sum(diff[0:zero])
    length = a + sum(diff[zero:]) + \
        min(a, sum(diff[zero:]))
else:
    length = sum(diff)
print(length)

Submission status: Runtime Error

Solution code:
import sys

n, k = [int(n) for n in input().split(" ")]
fire = [int(n) for n in input().split(" ")]

if (n == 1):
    print(k * fire[0])
    sys.exit()
elif (k == 0):
    print(0)
    sys.exit()

diff = [0] * len(fire)
zero = -1

for i in range(0, len(diff)):
    if (zero == -1 and fire[i + 1] * fire[i] <= 0):
        fire.insert(i + 1, 0)
        zero = i + 1

    diff[i] = fire[i + 1] - fire[i]

if (zero == -1):
    fire.append(0)
    zero = len(fire - 1)

for i in range(0, n - k):
    if (zero == 0 or diff[0] < diff[-1]):
        diff.pop()
        fire.pop()
    elif (diff[-1] > diff[0]):
        diff.pop(0)
        fire.pop(0)
        zero -= 1
    elif (abs(fire[0]) > abs(fire[-1])):
        diff.pop(0)
        fire.pop(0)
        zero -= 1
    else:
        diff.pop()
        fire.pop()

length = sum(diff[0:zero]) + sum(diff[zero:]) + \
    min(sum(diff[0:zero]), sum(diff[zero:]))
print(length)

Submission status: Runtime Error

Solution code:
import sys

n, k = [int(n) for n in input().split(" ")]
fire = [int(n) for n in input().split(" ")]

if (n == 1):
    print(k * fire[0])
    sys.exit()
elif (k == 0):
    print(0)
    sys.exit()

diff = [0] * len(fire)
zero = -1

for i in range(0, len(diff)):
    if (zero == -1 and fire[i + 1] * fire[i] <= 0):
        fire.insert(i + 1, 0)
        zero = i + 1

    diff[i] = fire[i + 1] - fire[i]

if (zero == -1):
    fire.append(0)
    zero = len(fire - 1)

for i in range(0, n - k):
    if (diff[0] > diff[-1]):
        diff.pop(0)
        fire.pop(0)
        zero -= 1
    elif (diff[-1] > diff[0]):
        diff.pop()
        fire.pop()
    elif (abs(fire[0]) > abs(fire[-1])):
        diff.pop(0)
        fire.pop(0)
        zero -= 1
    else:
        diff.pop()
        fire.pop()

length = sum(diff[0:zero]) + sum(diff[zero:]) + \
    min(sum(diff[0:zero]), sum(diff[zero:]))
print(length)

Submission status: Runtime Error

Solution code:
import sys

n, k = [int(n) for n in input().split(" ")]
fire = [int(n) for n in input().split(" ")]

if (n == 1):
    print(k * fire[0])
    sys.exit()

diff = [0] * len(fire)
zero = -1

for i in range(0, len(diff)):
    if (zero == -1 and fire[i + 1] * fire[i] <= 0):
        fire.insert(i + 1, 0)
        zero = i + 1

    diff[i] = fire[i + 1] - fire[i]

for i in range(0, n - k):
    if (diff[0] > diff[-1]):
        diff.pop(0)
        fire.pop(0)
        zero -= 1
    elif (diff[-1] > diff[0]):
        diff.pop()
        fire.pop()
    elif (abs(fire[0]) > abs(fire[-1])):
        diff.pop(0)
        fire.pop(0)
        zero -= 1
    else:
        diff.pop()
        fire.pop()

length = sum(diff[0:zero]) + sum(diff[zero:]) + \
    min(sum(diff[0:zero]), sum(diff[zero:]))
print(length)

Submission status: Runtime Error

Solution code:
import sys

n, k = [int(n) for n in input().split(" ")]
fire = [int(n) for n in input().split(" ")]

if (n == 1):
    print(k * fire[0])
    sys.exit()

diff = [0] * len(fire)
zero = -1

for i in range(0, len(diff)):
    if (zero == -1 and fire[i + 1] * fire[i] <= 0):
        fire.insert(i + 1, 0)
        zero = i + 1

    diff[i] = fire[i + 1] - fire[i]

for i in range(0, n - k):
    if (diff[0] > diff[-1]):
        diff.pop(0)
        fire.pop(0)
        zero -= 1
    elif (diff[-1] > diff[0]):
        diff.pop()
        fire.pop()
    elif (abs(fire[0]) > abs(fire[-1])):
        diff.pop(0)
        fire.pop(0)
        zero -= 1
    else:
        diff.pop()
        fire.pop()

length = sum(diff[0:zero]) + sum(diff[zero:]) + \
    min(sum(diff[0:zero]), sum(diff[zero:]))
print(fire)
print(diff)
print(length)

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!

import bisect
from collections import defaultdict
 
N, K = map(int, input().rstrip().split(' '))
X = sorted(list(map(int, input().rstrip().split(' '))))

i = bisect.bisect_left(X, 0)
X.insert(i, 0)

memo = defaultdict(lambda: defaultdict(lambda: -1))
 
def recursive(current_k, cost, i, left_i, right_i):
    if K == current_k:
        return cost
    if memo[current_k][i] != -1:
        return memo[current_k][i]
       
    left_cost = 1e10 
    if left_i >= 0:
        left_cost = recursive(current_k + 1, cost + X[i] - X[left_i], left_i, left_i - 1, right_i)
        
    right_cost = 1e10
    if right_i <= N:
        right_cost = recursive(current_k + 1, cost + X[right_i] - X[i], right_i, left_i, right_i + 1)
        
    min_cost = min(left_cost, right_cost)
    
    memo[current_k][i] = min_cost
    
    return min_cost
    
print(recursive(0, 0, i, i - 1, i + 1))

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!

N, K = map(int, input().rstrip().split(' '))
X = sorted(list(map(int, input().rstrip().split(' '))) + [0])

#N = int(1e8)
#K = int(3)

#X = list(range(N))

#print(X)

i = 0
while True:
    if X[i] == 0:
        break
    i += 1

memo = [[-1] * (N + 1) for _ in range(K)]

def recursive(current_k, cost, i, left_i, right_i):
    if K == current_k:
        return cost
    if memo[current_k][i] != -1:
        return memo[current_k][i]
        
    left_cost = 1e10 
    right_cost = 1e10
    if left_i >= 0 and right_i <= N:
        if left_i >= 0:
            left_cost = recursive(current_k + 1, cost + X[i] - X[left_i], left_i, left_i - 1, right_i)
        if right_i <= N:
            right_cost = recursive(current_k + 1, cost + X[right_i] - X[i], right_i, left_i, right_i + 1)
    elif left_i >= 0:
        left_cost = cost + X[i] - X[left_i - (K - current_k)]
    else:
        right_cost = cost + X[right_i + (K - current_k)] - X[i]
    
    min_cost = min(left_cost, right_cost)
    
    memo[current_k][i] = min_cost
    
    return min_cost
    
print(recursive(0, 0, i, i - 1, i + 1))

Submission status: Runtime Error

Solution code:
N, K =map(int,input().split())
x = list(map(int,input().split()))
a = 0
for i in range(100000):
    if x[i] >= 0:
        a = i
        break
s = x[a+K-1]
#print(K,s)
if a == 0:
    print(s)
else:
    for i in range(1, K):
        s = min(s,x[a+K-1-i]-x[a-i]+min(x[a+K-1-i],-x[a-i]))
    print(s)

Submission status: Runtime Error

Solution code:
import bisect

N, K = [int(item) for item in input().split()]
x = [int(item) for item in input().split()]

sep = bisect.bisect(x, 0)

R = x[:sep][::-1] + [-10**7]
L = x[sep:] + [10**7]

for i in range(len(R)):
  R[i] = -R[i]
  
ans = 10**6
if K < len(R):
  ans = min(R[K-1], ans)
if K < len(L):
  ans = min(L[K-1], ans)
  
for i in range(len(R)):
  if K-(i+1)-1 >= 0 and len(L) is not 0:
    ans = min(ans, R[i]*2 + L[K-(i+1)-1])
for i in range(len(L)):
  if K-(i+1)-1 >= 0 and len(R) is not 0:
    ans = min(ans, L[i]*2 + R[K-(i+1)-1])
  
print(ans)

Submission status: Runtime Error

Solution code:
import bisect

N, K = [int(item) for item in input().split()]
x = [int(item) for item in input().split()]

sep = bisect.bisect(x, 0)

R = x[:sep][::-1]
L = x[sep:]

for i in range(len(R)):
  R[i] = -R[i]

ans = 10**6
for i, r in enumerate(R):
  ans = min(ans, r*2+ L[K-(i+1)-1])
for i, l in enumerate(L):
  ans = min(ans, l*2+ R[K-(i+1)-1])
  
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np

N, K = (int(i) for i in input().split())
x = np.sort(np.array([int(i) for i in input().split()]))

result = []
if(N==1):
    print(x[0])
else:
    for i in range(N - K + 1):
        left = x[i]
        right = x[i + K - 1]

        if (left * right < 0):
            if (np.abs(left) < np.abs(right)):
                diff = np.abs(left) * 2 + np.abs(right)
            else:
                diff = np.abs(left) + np.abs(right) * 2

        else:
            diff = np.max([left, right])

        result.append(diff)

#print(result)
print(np.min(result))

Submission status: Runtime Error

Solution code:
import numpy as np

N, K = (int(i) for i in input().split())
x = np.sort(np.array([int(i) for i in input().split()]))

result = []
if(N==1):
    print(x[0])
    exit()
else:
    for i in range(N - K):
        left = x[i]
        right = x[i + K - 1]

        if (left * right < 0):
            if (np.abs(left) < np.abs(right)):
                diff = np.abs(left) * 2 + np.abs(right)
            else:
                diff = np.abs(left) + np.abs(right) * 2

        else:
            diff = np.max([left, right])

        result.append(diff)

print(np.min(result))

Submission status: Runtime Error

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: Runtime Error

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

# 累積和を使う
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
    #  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:
        # 全部右側
        try:
            results.append(distances[end-1])
        except:
            break
    else:
        results.append(distances[start])

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

Submission status: Runtime Error

Solution code:
MAX = 300000001

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


def main():
    ans = MAX

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

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

    for i in range(N):
        if xn[i] <= 0 and 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: Runtime Error

Solution code:
from collections import Counter
import numpy as np
H, W = map(int, input().split())
a = []
r_idx = []
c_idx = []
#a.shape = (H, W)
for i in range(H):
    line = list(input())
    if Counter(line).most_common()[0][1] != W:
        r_idx.append(i)
    a.append(line)
a = np.array(a).T
#a.shape = (W, H)
b = []
for i in range(W):
    if Counter(a[i]).most_common()[0][1] == H:
        continue
    b.append(a[i])

b = np.array(b).T
c = []
for idx in r_idx:
    c.append(b[idx])

for i in range(len(c)):
    print("".join(c[i]))

Submission status: Runtime Error

Solution code:
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: Runtime Error

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.sppend(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: Runtime Error

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)

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

    for i in range(1, K):  # 左側からいくつ取るか
        if i > pos - 1:  # 左側に取れるだけ数がないなら continue
            continue
        # min(一番左までの距離 x 往復 + 一番右までの距離, 一番右までの距離 x 往復 + 一番左までの距離)
        ans = min(ans, abs(X[pos - i]) * 2 + abs(X[pos + K - i - 1]))
        ans = min(ans, abs(X[pos + K - i - 1]) * 2 + abs(X[pos - i]))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

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)
    ans = INF
    if N - pos + 1 >= K: # 右側からだけ取れるなら
        ans = min(ans, abs(X[pos + K - 1]))
    # print(ans)
    if pos - 1 >= K: # 左側からだけ取れるなら
        ans = min(ans, abs(X[pos - K]))
    # print(ans)

    for i in range(1, K):  # 左側からいくつ取るか
        if not i < pos - 1:  # 左側に取れるだけ数がないなら continue
            continue
        # min(一番左までの距離 x 往復 + 一番右までの距離, 一番右までの距離 x 往復 + 一番左までの距離)
        ans = min(ans, abs(X[pos - i]) * 2 + abs(X[pos + K - i - 1]))
        ans = min(ans, abs(X[pos + K - i - 1]) * 2 + abs(X[pos - i]))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import bisect

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

if 0 in X:
  K=K-1

Right=[]
Left=[]
  
for x in X:
  if x>0:
    Right.append(x):
  else:
    Left=[abs(x)]+Left

print(Right)
print(Left)

Submission status: Runtime Error

Solution code:
import itertools
n,k=map(int,input().split())
x=[int(i) for i in input().split()]
kumi=list(itertools.combinations(x, k))
ans=9999999999
l=0
r=0
for i in kumi:
    l=abs(i[0])+abs(i[-1]-i[0])
    r=abs(i[-1])+abs(i[0]-i[-1])
    memo=min(l,r)
    if ans>memo:
        ans=memo
print(min(ans))

Submission status: Runtime Error

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():
    global N, K, results
    results = []
    N, K = LI()
    X = LI()
    # すべて正にする
    if N == 1 and K == 1 and X == [0]:
        print(0)
        return
    count = 0
    if 0 in X:
        X.remove(0)
        count += 1
    min_x = min(X)
    if min_x < 0:
        X = [x - min_x for x in X]
        # 貪欲的にいく？
        dfs(-min_x, 0, X, 0, count)
    else:
        dfs(0, 0, X, 0, count)

    print(min(results))


def dfs(p, s, rest, pidx, count):
    global N, K, results
    # 該当のものを使うか
    # 右に行くか左に行くかの判断
    # k個選んだら終了
    if count == K:
        results.append(s)
        return

    if rest[-1] < p:
        # 右側には数字がない
        #  for idx, i in enumerate(rest):
        #      if idx > K - count - 1:
        #          results.append(s)
        #          return
        #      if idx == 0:
        #          s += 
        dfs(rest[-1], s+p-rest[-1], rest[:-1], 0, count+1)
        return

    if rest[0] > p:
        # 左側に数字がない
        # K個選んで終わり
        for idx, i in enumerate(rest):
            if idx > K - count - 1:
                results.append(s)
                return
            if idx == 0:
                s += i - p
            else:
                s += i - rest[idx-1]
        #  dfs(rest[0], s+rest[0] - p, rest[1:], 0, count+1)
        return

    if pidx == 0:
        for ridx, r in enumerate(rest):
            if r > p:
                left = rest[ridx - 1]
                new_rest = rest[:ridx-1] + rest[ridx:]
                dfs(left, s + p - left, new_rest, ridx - 1, count+1)

                right = r
                new_rest = rest[:ridx] + rest[ridx+1:]
                dfs(right, s + right - p, new_rest, ridx, count+1)
                return
    else:
        left = rest[pidx - 1]
        new_rest = rest[:pidx-1] + rest[pidx:]
        dfs(left, s+p-left, new_rest, pidx - 1, count+1)

        right = rest[pidx]
        new_rest = rest[:pidx] + rest[pidx+1:]
        dfs(right, s+right - p, new_rest, pidx, count+1)



if __name__ == "__main__":
    main()

Submission status: Runtime Error

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():
    global N, K, results
    results = []
    N, K = LI()
    X = LI()
    # すべて正にする
    if N == 1 and K == 1 and X == [0]:
        print(0)
        return
    count = 0
    if 0 in X:
        X.remove(0)
        count += 1
    min_x = min(X)
    if min_x < 0:
        X = [x - min_x for x in X]
        # 貪欲的にいく？
        dfs(-min_x, 0, X, 0, count)
    else:
        dfs(0, 0, X, 0, count)

    print(min(results))


def dfs(p, s, rest, pidx, count):
    global N, K, results
    # 該当のものを使うか
    # 右に行くか左に行くかの判断
    # k個選んだら終了
    if count == K:
        results.append(s)
        return

    if rest[-1] < p:
        # 右側には数字がない
        dfs(rest[-1], s+p-rest[-1], rest[:-1], 0, count+1)
        return

    if rest[0] > p:
        # 左側に数字がない
        # K個選んで終わり
        for idx, i in enumerate(rest):
            if idx > K - count - 1:
                results.append(s)
                return
            if idx == 0:
                s += i
            else:
                s += i - rest[idx-1]
        #  dfs(rest[0], s+rest[0] - p, rest[1:], 0, count+1)
        return

    if pidx == 0:
        for ridx, r in enumerate(rest):
            if r > p:
                left = rest[ridx - 1]
                new_rest = rest[:ridx-1] + rest[ridx:]
                dfs(left, s + p - left, new_rest, ridx - 1, count+1)

                right = r
                new_rest = rest[:ridx] + rest[ridx+1:]
                dfs(right, s + right - p, new_rest, ridx, count+1)
                return
    else:
        left = rest[pidx - 1]
        new_rest = rest[:pidx-1] + rest[pidx:]
        dfs(left, s+p-left, new_rest, pidx - 1, count+1)

        right = rest[pidx]
        new_rest = rest[:pidx] + rest[pidx+1:]
        dfs(right, s+right - p, new_rest, pidx, count+1)



if __name__ == "__main__":
    main()

Submission status: Runtime Error

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():
    global N, K, results
    results = []
    N, K = LI()
    X = LI()
    # すべて正にする
    if N == 1 and K == 1 and X == [0]:
        print(0)
        return
    min_x = min(X)
    if min_x < 0:
        X = [x - min_x for x in X]
        # 貪欲的にいく？
        dfs(-min_x, 0, X, 0, 0)
    else:
        dfs(0, 0, X, 0, 0)

    print(min(results))


def dfs(p, s, rest, pidx, count):
    global N, K, results
    # 該当のものを使うか
    # 右に行くか左に行くかの判断
    # k個選んだら終了
    if count == K:
        results.append(s)
        return

    if rest[-1] < p:
        # 右側には数字がない
        dfs(rest[-1], s+p-rest[-1], rest[:-1], 0, count+1)
        return

    if rest[0] > p:
        # 左側に数字がない
        # K個選んで終わり
        for idx, i in enumerate(rest):
            if idx > K - count - 1:
                results.append(s)
                return
            if idx == 0:
                s += i
            else:
                s += i - rest[idx-1]
        #  dfs(rest[0], s+rest[0] - p, rest[1:], 0, count+1)
        return

    if pidx == 0:
        for ridx, r in enumerate(rest):
            if r > p:
                left = rest[ridx - 1]
                new_rest = rest[:ridx-1] + rest[ridx:]
                dfs(left, s + p - left, new_rest, ridx - 1, count+1)

                right = r
                new_rest = rest[:ridx] + rest[ridx+1:]
                dfs(right, s + right - p, new_rest, ridx, count+1)
                return
    else:
        left = rest[pidx - 1]
        new_rest = rest[:pidx-1] + rest[pidx:]
        dfs(left, s+p-left, new_rest, pidx - 1, count+1)

        right = rest[pidx]
        new_rest = rest[:pidx] + rest[pidx+1:]
        dfs(right, s+right - p, new_rest, pidx, count+1)



if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

list_original.append(0)
list = sorted(list_original)
point = list.index(0)

if k <= point and point <= n-k+1:
    if abs(list[point-k]) <= list[point+k]:
        print(abs(list[point-k]))
    else:
        print(list[point])
elif point < k:
    print(list[point+k])
else:
    print(abs(list[point-k]))