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

    Ps, Ng = [], []

    for a in A:
        if a > 0:
            Ps.append(a)
        else:
            Ng.append((-1) * a)

    Ps.sort()
    Ng.sort()

    ans = 10**20

    # goto right
    if len(Ps):
        for turn in range(K-len(Ng)-1, min(K, len(Ps))):
            dist = Ps[turn]

            if turn != K - 1:
                dist += Ps[turn] + Ng[K - turn - 2]

            if dist < ans:
                ans = dist

    # goto left
    if len(Ng):
        for turn in range(K-len(Ps)-1, min(K, len(Ng))):
            dist = Ng[turn]

            if turn != K - 1:
                dist += Ng[turn] + Ps[K - turn - 2]

            if dist < ans:
                ans = dist

    print(ans)





main()

Submission status: Accepted

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

N = int(N)
K = int(K)

xList = [int(x) for x in input().split()]

cache = 99999999999
for a, b in zip(xList, xList[K-1:]):
    if min(a,b) < 0 and 0 <= max(a,b):
        if (max(a,b) - min(a,b) + min(abs(a),abs(b))) < cache:
            cache = (max(a,b) - min(a,b) + min(abs(a),abs(b)))
    elif a < 0 and b < 0:
        if abs(a) < cache:
            cache = abs(a)
    else:
        if abs(b) < cache:
            cache = abs(b)

print(cache)

Submission status: Accepted

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

L = N-K+1
Y = [10**9]*(L)
for i in range(L):
    a = X[i]
    b = X[i+K-1]
    if a*b<0:
        Y[i] = 2*min(abs(a), abs(b)) + max(abs(a), abs(b))
    else:
        Y[i] = max(abs(a), abs(b))

print(min(Y))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
X=list(map(int,input().split()))
time=[]
zero=0
if 0 in X:
    zero=X.index(0)
    for i in range(N):
        if zero+i<N and zero-K+1+i>=0:
            time.append(min(abs(X[zero-K+1+i]),abs(X[zero+i]))+abs(X[zero-K+1+i])+abs(X[zero+i]))
else:
    g=1
    for i in range(N-1):
        if X[i]<0 and X[i+1]>0:
            g=0
            zero=i
            break
    if g==1:
        if X[0]<0:
            time.append(-X[-K])
        else:
            time.append(X[K-1])
        exit
    for i in range(N):
        if zero+i<N and zero-K+1+i>=0:
            time.append(min(abs(X[zero-K+1+i]),abs(X[zero+i]))+abs(X[zero-K+1+i])+abs(X[zero+i]))
print(min(time))

Submission status: Accepted

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

for i in range(n-k+1):
  dist=x[k+i-1]-x[i]+min(abs(x[k+i-1]),abs(x[i]))
  if dist < ans:
    ans = dist
    
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from statistics import mean, median,variance,stdev
import numpy as np
import sys
import math
import fractions

def j(q):
    if q==1: print("Yes")
    else:print("No")
    exit(0)


def ct(x,y):
    if (x>y):print("")
    elif (x<y): print("")
    else: print("")

def ip():
    return int(input())


#n = ip()                              #入力整数1つ
x,y= (int(i) for i in input().split())      #入力整数横2つ
#n,x,y = (int(i) for i in input().split())    #入力整数横3つ
#n,m,x,y= (int(i) for i in input().split())  #入力整数横4つ
a = [int(i) for i in input().split()]        #入力整数配列
#a = input()                                  #入力文字列
#a = input().split()                          #入力文字配列
#n = ip()                      #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(n)]    #入力セット(整数改行あり)(2/2)

#jの変数はしようできないので注意
#全足しにsum変数使用はsum関数使用できないので注意
s = []
if x == 1:
    print(a[0])
    exit(0)
if x == y:
    c = a[0]
    d = a[x-1]
    if c*d < 0:
        s.append(d-c + min(abs(c),abs(d)))
    elif  d <= 0:
        s.append(abs(c))
    else: s.append(d)
for i in range(x-y+1):
    c = a[i]
    d = a[i+y-1]
    if c*d < 0:
        s.append(d-c + min(abs(c),abs(d)))
    elif  d <= 0:
        s.append(abs(c))
    else: s.append(d)
print(min(s))

Submission status: Accepted

Solution code:
import sys

def main():
  input = sys.stdin.readline
  N, K = map(int, input().split())
  X = list(map(int, input().split()))
  
  ans = float('inf')
  for i in range(N-K+1):
    L = X[i]
    R = X[i+K-1]
    if L * R < 0:
      t = min(abs(L) + (R - L), R + (R - L))
    else:
      t = max(abs(L), abs(R))
    ans = min(ans, t)
  
  print(ans)


if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
# C
N, K = map(int, input().split())
X = list(map(int, input().split()))
result = []
for l, r in zip(X,X[K-1:]):
    result.append(r - l + min(abs(l), abs(r)))
print(min(result))

Submission status: Accepted

Solution code:
n=list(map(int,input().split()))
Y=list(map(int,input().split()))
P=[i for i in Y if i>=0]
M=[i*-1 for i in Y if i<0]
#P,M==[]時のerror処理として大きな数を追加
if P==[]:
    P.append(max(M)*1000)
if M==[]:
    M.append(max(P)*1000)
p=sorted(P)
m=sorted(M)
L1=[]
L2=[]
#Index　out of range はあらかじめifで範囲を超えないようにしておく
for i in range(n[1]):
    if n[1]-i-2<len(m) and i<len(p):
        L1.append(p[i]+m[n[1]-i-2]*2)
        L2.append(p[i]*2+m[n[1]-i-2])
if len(p)>=n[1]:
    L1.append(p[n[1]-1])
if len(m)>=n[1]:
    L2.append(m[n[1]-1])
print(min(min(L1),min(L2)))

Submission status: Accepted

Solution code:
n=list(map(int,input().split()))
Y=list(map(int,input().split()))
P=[i for i in Y if i>=0]
M=[i*-1 for i in Y if i<0]
if P==[]:
    P.append(max(M)*1000)
if M==[]:
    M.append(max(P)*1000)
p=sorted(P)
m=sorted(M)
L1=[]
L2=[]
for i in range(n[1]):
    if n[1]-i-2<len(m) and i<len(p):
        L1.append(p[i]+m[n[1]-i-2]*2)
        L2.append(p[i]*2+m[n[1]-i-2])
if len(p)>=n[1]:
    L1.append(p[n[1]-1])
if len(m)>=n[1]:
    L2.append(m[n[1]-1])
print(min(min(L1),min(L2)))

Submission status: Accepted

Solution code:
N, K  = map(int,input().split())
L =list(map(int,input().split()))
Lzero = list(filter(lambda x:x==0,L))
Lright = list(filter(lambda x:x>0,L))
Lleft = list(map(lambda x:abs(x),filter(lambda x:x<0,L)))[::-1]
K -= len(Lzero)
if K <= 0:
    print(0)
    quit()

dis = []
if len(Lright) == 0:
    print(Lleft[K-1])
    quit()
if len(Lleft) == 0:
    print(Lright[K-1])
    quit()
try :
    dis.append(Lright[K-1])
    dis.append(Lleft[K-1])
except:
    pass


for i in range(len(Lright)):
    remain = K
    if i+1 >K:
        break
    elif i+1 == K:
        dis.append(Lright[i])
        break
    d = 2*Lright[i]
    remain -= (i+1)
    try :
        d += Lleft[remain-1]
        dis.append(d)
    except:
        pass
for i in range(len(Lleft)):
    remain = K
    if i+1 >K:
        break
    elif i+1 == K:
        dis.append(Lleft[i])
        break
    d = 2*Lleft[i]
    remain -= (i+1)
    try:
        d += Lright[remain-1]
        dis.append(d)
    except:
        pass
print(min(dis))

Submission status: Accepted

Solution code:
N, K = map(int,input().split())
X = list(map(int,input().split()))
tmp = []
for l, r in zip(X,X[K-1:]):
  tmp.append(r - l + min(abs(l), abs(r)))
print(min(tmp))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
X=list(map(int,input().split()))
cost=float('inf')
for i in range(n-k+1):
    l=X[i]
    r=X[i+k-1]
    if l<=0:
        if r<=0:
            tmp=-l
        else:
            tmp_l=-l*2+r
            tmp_r=2*r-l
            tmp=min(tmp_l,tmp_r)
    else:
        tmp=r
    cost=min(cost,tmp)
print(cost)

Submission status: Accepted

Solution code:
class Solver(object):
    def __init__(self):
        self.n, self.k = list(map(int, input().split(" ")))
        self.x_s = sorted(list(map(int, input().split(" "))))
 
    def solve(self):
        candidates = []
        for i in range(self.n - self.k + 1):  # 0 .. n-k
            candidates.append((i, i + self.k - 1))
            # print(self.x_s[i:i+self.k])
        best_candidate = candidates[0]
        best_distance = self.distance(best_candidate)
        for c in candidates[1:]:
            d = self.distance(c)
            if d < best_distance:
                best_candidate = c
                best_distance = d
        # print(best_candidate)
        print(best_distance)
 
    def distance(self, candidate):
        left = self.x_s[candidate[0]]
        right = self.x_s[candidate[1]]
        # X X X 0
        if right <= 0:
            return abs(left)
        # 0 X X X
        elif left >= 0:
            return abs(right)
        # X 0 X X
        elif abs(left) < abs(right):
            return abs(left) + abs(left) + abs(right)
        # X X 0 X
        else:
            return abs(right) + abs(right) + abs(left)
 
    def filter(self):
        # Only want -k .. k elements
        right = None
        counter = 0
        for i, v in enumerate(self.x_s):
            if v >= 0:
                counter += 1
                if counter == self.k:
                    right = i + 1
                    break
        if right is None:
            right = len(self.x_s)
 
        left = None
        counter = 0
        for i, v in reversed(list(enumerate(self.x_s))):
            if v <= 0:
                counter += 1
                if counter == self.k:
                    left = i
                    break
        if left is None:
            left = 0
        return self.x_s[left:right]
 
 
if __name__ == "__main__":
    s = Solver()
    s.solve()

Submission status: Accepted

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

    n = []
    p = []
    ans = []
    for xi in x:
        if xi < 0:
            n.append(xi)
        else:
            p.append(xi)

    # print(n,p)

    # i: nから選ぶ個数
    # k-i: pから選ぶ個数
    for i in range(k+1):
        # print(i, k-i, k)
        if i > len(n):
            continue
        if k-i > len(p):
            continue

        if i == 0:
            ans.append(p[k-1])
        elif k - i == 0:
            ans.append(-n[-k])
        else:
            nd = -n[-i]
            pd = p[k-i-1]
            ans.append(nd + pd + min(nd, pd))

    # print(ans)
    print(min(ans))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np

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

array = np.array(lst)
po_array = array[array>=0]
ne_array = abs(array[array<0])
ne_array.sort()

if len(po_array) >= len(ne_array):
    long_array = po_array
    short_array = ne_array
else:
    long_array = ne_array
    short_array = po_array

if len(short_array) > k:
    min_len = k
else:
    min_len = len(short_array)
        
if min_len == 0:
    print(long_array[k-1])
else:
    min_dist = 10**10
    for i in range(min_len):
        dist = 10**10
        if i == k-1:
            dist = short_array[i]
        elif k-i-1 <= len(long_array): 
            dist = min(short_array[i]*2 + long_array[k-i-2], short_array[i] + long_array[k-i-2]*2)
        if min_dist > dist:
            min_dist = dist
    if len(long_array) >= k:
        if min_dist > long_array[k-1]:
            min_dist = long_array[k-1]
    print(min_dist)

Submission status: Accepted

Solution code:
def solve(N, K, Xs):
    plus = sorted([x for x in Xs if x >= 0])
    minus = sorted([abs(x) for x in Xs if x < 0])
    ans = 10 ** 9
    for i in range(0, K + 1):
        j = K - i
        if i <= len(plus) and i == K:
            p = plus[i-1]
            ans = min(ans, p)
        elif j <= len(minus) and j == K:
            m = minus[j-1]
            ans = min(ans, m)
        elif i <= len(plus) and j <= len(minus):
            p = plus[i - 1]
            m = minus[j - 1]
            ans = min(ans, p * 2 + m, m * 2 + p)

    return ans
  
if __name__ == "__main__":
    N, K = tuple(map(int, input().split(" ")))
    Xs = list(map(int, input().split(" ")))
    print(solve(N, K, Xs))

Submission status: Accepted

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python
N,K = map(int, input().split())
x = list(map(int, input().split()))

x_minus = filter(lambda x: x<0, x)
x_plus  = filter(lambda x: x>=0, x)

x_minus = sorted(x_minus, reverse=True)
x_plus  = sorted(x_plus , reverse=False)

n_minus = len(x_minus)
n_plus = len(x_plus)


ans = 10**9

# go left only
if n_minus >= K:
    # ans = min(ans, sum( map(lambda x: abs(x)m x_minus[K])))
    ans = min(ans, abs(x_minus[K-1]))

# go right only
if n_plus  >= K:
    # ans = min(ans, sum(x_plus[K-1]))
    ans = min(ans, x_plus[K-1])

# left   and  right
for i in range( min(K-1, n_minus) ):
    remain = K - i - 1
    try:
        ans = min(ans, 2*abs(x_minus[i]) + x_plus[K-i-1-1])
    except IndexError:
        continue
    
# right  and  left
for i in range( min(K-1, n_plus) ):
    remain = K - i - 1
    try: 
        ans = min(ans, 2*x_plus[i] + abs(x_minus[K-i-1-1]))
    except IndexError:
        continue

print(ans)

Submission status: Accepted

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

if len(x) == 1 and x[0] == 0:
    print(0)
    exit()

m = []
p = []
for i in range(n):
    if x[i] < 0:
        m.append(x[i])
    elif x[i] > 0:
        p.append(x[i])

ans = float('inf')
if len(m) >= k:
    ans = min(ans,abs(m[-k]))
    m = m[-k+1:]
if len(p) >= k:
    ans = min(ans,p[k-1])
    p = p[:k-1]

x = m+p
i = 0
for i in range(len(x)-k+1):
    ans = min(ans, min(abs(x[i])*2+abs(x[i+k-1]), abs(x[i])+abs(x[i+k-1])*2))

print(ans)

Submission status: Accepted

Solution code:
n,k = (int(i) for i in input().split())
x =list(int(i) for i in input().split())
a = [999999999999999]*(n-k+1)
for i in range(n-k+1):
  left =x[i]
  right =x[i+k-1]
  leftdistance = abs(left)+abs(right-left)
  rightdistance = abs(right)+abs(left-right)
  a[i] = min(leftdistance,rightdistance)
print(min(a))

Submission status: Accepted

Solution code:
import numpy as np

N,K = map(int,input().split())
x = list(map(int,input().split()))
min_t = None
for i in range(N-K+1):
  t = min(abs(x[i])+abs(x[i]-x[i+K-1]), abs(x[i+K-1])+abs(x[i]-x[i+K-1]))
  if min_t == None:
    min_t = t
  if min_t > t:
    min_t = t
print(min_t)

Submission status: Accepted

Solution code:
N, K = map(int,input().split())
X = list(map(int,input().split()))
result = []
for l, r in zip(X,X[K-1:]):
  result.append(r - l + min(abs(l), abs(r)))
print(min(result))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
x=list(map(int,input().split()))
ans=1000000000
for i in range(N-K+1):
    l=x[i]
    r=x[i+K-1]
    if ans>=min(abs(l)+abs(l-r),abs(r)+abs(l-r)):
        ans=min(abs(l)+abs(l-r),abs(r)+abs(l-r))
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int,input().split())
X = list(map(int,input().split()))
result = []
for l, r in zip(X,X[K-1:]):
  result.append((r - l + min(abs(l), abs(r))))
print(min(result))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
x = list(map(int,input().split()))
 
kyori=10**9
for i in range(n-k+1):
#print(x[i:k+i])
  if x[k+i-1]<=0:
    kyori = min(kyori,abs(x[i]))
  elif x[i]<0 and 0<x[k+i-1]:
    kyori = min(kyori,abs(x[i]*2)+abs(x[k+i-1]),abs(x[i])+abs(x[k+i-1]*2))
  elif 0<=x[i]:
    kyori = min(kyori,abs(x[k+i-1]))
print(kyori)

Submission status: Accepted

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

x.append(0)
x = sorted(x)
check = []
for i in range(n-k+1):
    a = abs(x[i])
    b = abs(x[i+k])
    check.append(max(a,b) + min(a,b) * 2)
print(min(check))

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] * x[i+k-1] < 0:
        ans.append(abs(x[i]) + abs(x[i+k-1]) + min(abs(x[i]), abs(x[i+k-1])))
    else:
        ans.append(max(abs(x[i]), abs(x[i+k-1])))
print(min(ans))

Submission status: Accepted

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

    i = 0
    ans = 10 ** 8 * n
    while i < n - k + 1:
        lr = abs(x[i]) + abs(x[i] - x[i + k - 1])
        rl = abs(x[i + k - 1]) + abs(x[i] - x[i + k - 1])
        i += 1
        ans = min(ans, lr, rl)
    print(ans)


main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
minval = 10000000000
for i in range(N-K+1):
    tmpval = abs(X[i]) + X[i+K-1] - X[i]
    if minval > tmpval:
        minval = tmpval
X = [-x for x in X[::-1]]
for i in range(N-K+1):
    tmpval = abs(X[i]) + X[i+K-1] - X[i]
    if minval > tmpval:
        minval = tmpval
print(minval)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
x = list(map(int,input().split()))
min_space = 10**9
for i in range(N-K+1):
    min_space = min(x[i+K-1] - x[i]+min(abs(x[i]),abs(x[i+K-1])),min_space)
# for i in range(N-K):
#     if x[i+K-1] - x[i]==min_space:
#         min_x = x[i]

print(min_space)

Submission status: Accepted

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

def main():
    na = list(map(int, input().split()))
    N, K = na[0], na[1]
    x = list(map(int, input().split()))

    l = bisect.bisect_left(x, 0)

    r = 3 * (10 ** 8)

    for i in range(min(l, K), -1, -1):
        if N < l + K - i:
            break
        if i == K:
            r = min(r, abs(x[l - K]))
        elif i == 0:
            r = min(r, abs(x[l + K - 1]))
        else:
            r = min(r, abs(x[l - i]) * 2 + x[l + K - i - 1], abs(x[l - i]) + x[l + K - i - 1] * 2)


    print(r)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

ans = 10 ** 9
for i in range(n - k + 1):
    L = A[i]
    R = A[i + k - 1]
    r1 = abs(L) - L + R
    r2 = abs(R) - L + R
    temp = min(r1, r2)
    ans = min(ans, temp)
    
print(ans)

Submission status: Accepted

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

cost_min = 999999999

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

print(cost_min)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
x = [int(i) for i in input().split()]
ans = float('inf')

for i in range(N - K + 1):
    ans = min(ans, min(abs(x[i]), abs(x[i+K-1])) + abs(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()))
y = []

for i in range(N-K+1):
    l1 = abs(x[i])
    l2 = abs(x[i+K-1])
    if x[i]* x[i+K-1] > 0:
        y.append(max(l1,l2))
    else:
        
        y.append(2*min(l1,l2) + max(l1,l2))

print(min(y))

Submission status: Accepted

Solution code:
def a():return input()#s
def ai():return int(input())#a,n or k
def ma():return map(int, input().split())#a,b,c,d or n,k
def ms():return map(str, input().split())#,a,b,c,d
def lma():return list(map(int, input().split()))#x or y
def lms():return list(map(str, input().split()))#x or y
a,b  = ma()
x = lma()
ans = 10 **18
for i in range(a-b+1):
    a0 = x[i]
    ab = x[i+b-1]
    if ab< 0 :
        ans = min(ans,abs(a0))
    elif a0 <=0 and 0 <= ab:
        ans = min(ans, ab-2*a0, 2*ab-a0)
    else:
        ans = min(ans,ab)
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter
from math import *
N, K = [int(x) for x in input().strip().split()]
x = [int(a) for a in input().strip().split()]
xpos = [0] + [a for a in x if a >= 0]
xneg = [0] + [abs(a) for a in x if a < 0]
xneg.sort()

timemin = 2**64
for i in range(0, min(len(xpos), K + 1)):
    posnum = i
    negnum = K - i
    if negnum >= len(xneg):
        continue
    time = xpos[posnum] * 2 + xneg[negnum]
    if time < timemin:
        timemin = time
for i in range(0, min(len(xneg), K + 1)):
    posnum = K - i
    negnum = i
    if posnum >= len(xpos):
        continue
    time = xneg[negnum] * 2 + xpos[posnum]
    if time < timemin:
        timemin = time

print(timemin)

Submission status: Accepted

Solution code:
N,K = (int(i) for i in input().split())
x = [int(i) for i in input().split()]
time=[]
for i in range(N-K+1):
    minSign='minus' if x[i]<0 else 'plus'
    maxSign='minus' if x[i+K-1]<0 else 'plus'
    if minSign=='minus' and maxSign=='minus':
        time.append(abs(x[i]))
    elif minSign=='plus' and maxSign=='plus':
        time.append(abs(x[i+K-1]))
    else:
        time.append(abs(x[i])+abs(x[i+K-1])+min(abs(x[i]),abs(x[i+K-1])))
print(min(time))

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):
    y0 = x[i]
    yk = x[i+K-1]
    if yk < 0:
        ans = min(ans, abs(y0))
    elif y0 <= 0 and 0 <= yk:
        ans = min(ans, yk-2*y0, 2*yk-y0)
    else:
        ans = min(ans, yk)

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
S = list(map(int,input().split()))
N = S[0]
K = S[1]
X = list(map(int,input().split()))

Xnegative = [abs(x) for x in X if x < 0]
Xpositive = [x for x in X if x >= 0]
Xnegative = sorted(Xnegative)

i = 0

if len(Xpositive) >= K:
    sub = Xpositive[K-1]
    while i < len(Xnegative) and K-i-2 >= 0:
        distance = min(Xnegative[i],Xpositive[K-2-i]) + Xnegative[i] + Xpositive[K-2-i]
        if sub > distance:
            sub = distance
        i = i + 1
elif len(Xpositive) == 0:
    sub = Xnegative[K-1]
else:
    l = K-len(Xpositive)
    sub = min(Xnegative[l-1],Xpositive[-1]) + Xnegative[l-1] + Xpositive[-1]
    while i + l < len(Xnegative) and -i-2 >= -len(Xpositive):
        distance = min(Xnegative[i+l],Xpositive[-i-2]) + Xnegative[i+l] + Xpositive[-i-2]
        if sub > distance:
            sub = distance
        i = i + 1

print(sub)

Submission status: Accepted

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

ans = 10 ** 5 * n
for i in range(n-k+1):
    l = A[i]
    r = A[i+k-1]
    route1 = abs(l) - l + r
    route2 = abs(r) + r - l
    temp = min(route1, route2)
    ans = min(ans, temp)
    
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

# 飛び飛びで塗ることはない -> X[i] ~ X[i + k - 1] を全て塗る
# i = 1, ..., n - k + 1 について所要時間を調べる
# 原点 -> X[i] -> X[i + k - 1] or 原点 -> X[i + k - 1] -> X[i]
D = []
for i in range(n - k + 1):
    t1 = abs(X[i]) + (X[i + k - 1] - X[i])
    t2 = abs(X[i + k - 1]) + (X[i + k - 1] - X[i])
    D.append(min(t1, t2))

print(min(D))

Submission status: Accepted

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

for i in range(n - k + 1):
    L = A[i]
    R = A[i + k -1]
    dist = min(abs(L) - L + R, abs(R) + R - L)
    D.append(dist)
    
print(min(D))

Submission status: Accepted

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

Submission status: Accepted

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

ans = INF
for li in range(n - k + 1):
    ri = k + li - 1
    t = min(abs(x[li]) + abs(x[ri] - x[li]), abs(x[ri]) + abs(x[li] - x[ri]))
    ans = min(t, ans)

print(ans)

Submission status: Accepted

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

def sign(x):
    return int(x >= 0)

ans = INF
for i in range(n - k + 1):
    p = k + i - 1
    if sign(x[i]) == sign(x[p]):
        t = max(abs(x[i]), abs(x[p]))
    else:
        t = min(-x[i] * 2 + x[p], -x[i] + x[p] * 2)
    if t < ans:
        ans = t

print(ans)

Submission status: Accepted

Solution code:
b = list(map(int, input().split()))
a = list(map(int, input().split()))
x = b[0]-b[1]+1
res = 10**15
 
for i in range(x):
    tmp = i + b[1] - 1
    if res > (a[tmp]-a[i] + min(abs(a[i]),abs(a[tmp]))):
	    res = a[tmp]-a[i] + min(abs(a[i]),abs(a[tmp]))
        
print(res)

Submission status: Accepted

Solution code:
import numpy as np
b = list(map(int, input().split()))
a = list(map(int, input().split()))
x = b[0]-b[1]+1
res = 10**15
 
for i in range(x):
    tmp = i + b[1] - 1
    if res > (a[tmp]-a[i] + min(abs(a[i]),abs(a[tmp]))):
	    res = a[tmp]-a[i] + min(abs(a[i]),abs(a[tmp]))
        
print(res)

Submission status: Accepted

Solution code:
import numpy as np
b = list(map(int, input().split()))
a = list(map(int, input().split()))
x = b[0]-b[1]+1
res = 10**100
 
for i in range(x):
    tmp = i + b[1] - 1
    res = min( a[tmp]-a[i] + min(abs(a[i]),abs(a[tmp])),res)
        
print(res)

Submission status: Accepted

Solution code:
#横にn個入力
n, k = map(int, input().split())

#n...普通、a...横で入力された複数の要素を配列で取得
a = input().split()

x = [int(m) for m in a]
lx = []
mx = []
rx = []
for i in range(n):
    if x[i] < 0:
        lx.append(x[i])
    elif x[i] == 0:
        mx.append(x[i])
    else:
        rx.append(x[i])

lx.sort(reverse=True)
rx.sort()
lmx = lx + mx
lmx.sort(reverse=True)
ans1 = float("INF")
if len(lmx) >= k:
    ans1 = abs(lmx[k - 1])

mrx = mx + rx
mrx.sort()
ans2 = float("INF")
if len(mrx) >= k:
    ans2 = abs(mrx[k - 1])

p = 1
ans3 = float("INF")
while p <= len(rx):
    if len(rx) >= p and len(lx) >= k - p - len(mx) and k - p - len(mx) > 0:
        if ans3 > abs(2 * rx[p - 1]) + abs(lx[k - p - len(mx) - 1]):
            ans3 = abs(2 * rx[p - 1]) + abs(lx[k - p - len(mx) - 1])
    p += 1

q = 1
ans4 = float("INF")
while q <= len(lx):
    if len(lx) >= q and len(rx) >= k - q - len(mx) and k - q - len(mx) > 0:
        if ans4 > abs(2 * lx[q - 1]) + abs(rx[k - q - len(mx) - 1]):
            ans4 = abs(2 * lx[q - 1]) + abs(rx[k - q - len(mx) - 1])
    q += 1

print(min(ans1,ans2,ans3,ans4))