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

input = sys.stdin.readline


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

    n_zero = x.count(0)
    if n_zero >= K:
        print(0)
        exit()
    
    K -= n_zero
    A = []  # < 0
    B = []  # > 0
    for _x in x:
        if _x < 0:
            A.append(-_x)
        elif _x > 0:
            B.append(_x)
    A = A[::-1][:K]
    B = B[:K]
    ans = float("INF")

    for n_A in reversed(range(len(A) + 1)):
        n_B = K - n_A
        if n_B > len(B):
            break

        if n_A == 0 and n_B == K:
            ans = min(ans, B[-1])
        elif n_A == K and n_B == 0:
            ans = min(ans, A[-1])
        else:
            a = A[n_A - 1]
            b = B[n_B - 1]
            time = a + b + min(a, b)
            ans = min(ans, time)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
@author: H_Hoshigi
"""
def main():
    N, K = map(int, input().split())
    x_lsit = list(map(int, input().split()))
    INF = pow(10, 9)

    min_time = INF
    for i in range(N-K+1):
        x_l = x_lsit[i]
        x_r = x_lsit[i+K-1]
        this_time = int()
        if x_l <= -1:
            if x_r <= 0:
                this_time = -x_l
            else:
                this_time = min(-x_l, x_r)*2 + max(-x_l, x_r)
        else:
            this_time = x_r
        min_time = min(min_time, this_time)
    print(min_time)
    return

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,k,*x=map(int,open(0).read().split())
ans=float('inf')
if 0 in x:
  k-=1
  n-=1
  del x[x.index(0)]

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

Submission status: Accepted

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

ls_posi = []#0を含む
ls_nega = []

for i in range(n):
    if x[i] < 0:
        ls_nega.append(-x[i])
    else:
        ls_posi.append(x[i])

ls_nega.reverse()
ans = 10 ** 9

for i in range(k+1):
    #posiから0〜k個, negaからk-posi個
    if i == 0:
        if len(ls_nega) >= k:
            ans = min(ans,ls_nega[k-1])
    elif i == k:
        if len(ls_posi) >= k:
            ans = min(ans,ls_posi[k-1])
    else:
        if len(ls_posi) >= i and len(ls_nega) >= k - i:
            ans = min(ans,ls_posi[i-1] * 2 + ls_nega[k-i-1])
            ans = min(ans,ls_posi[i-1] + ls_nega[k-i-1] * 2)
print(ans)

Submission status: Accepted

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

lis = []
for i in range(N-K+1):
    left = X[i]
    right = X[i+K-1]
    res = right - left
    abs_l, abs_r = abs(left), abs(right)
    if abs_l > abs_r: 
       res += abs_r
    else:
       res += abs_l
    lis.append(res)
print(min(lis))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
ans = 10**20
for i in range(N-K+1):
  l = X[i]
  r = X[i+K-1]
  if l*r >= 0:
    ans = min(ans, max(abs(l), abs(r)))
  else:
    ans = min(ans, r-l + min(abs(l), abs(r)))
print(ans)

Submission status: Accepted

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

ans = 10 ** 9
for i in range(n - k + 1):
    if xx[i + k - 1] <= 0:
        ans = min(ans, -xx[i])
    elif xx[i] >= 0:
        ans = min(ans, xx[i + k - 1])
    else: #if xx[i] <= 0 and xx[i + k - 1] >= 0:
        ans = min(
            ans,
            -xx[i] * 2 + xx[i + k - 1],
            -xx[i] + 2 * xx[i + k - 1]
        )
print(ans)

Submission status: Accepted

Solution code:
import bisect

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

rlt = float('inf')
i = bisect.bisect_left(Xs, 0)
if i-K >= 0:
  rlt = abs(Xs[i-K])

for j in range(i, i+K-1):
  if j >= N:
    break
  if j - K + 1 < 0:
    continue
  rlt = min(rlt, 2*abs(Xs[j-K+1])+Xs[j], abs(Xs[j-K+1])+2*Xs[j])
  
if i + K - 1 < N:
  rlt = min(rlt, Xs[i+K-1])
  
print(rlt)

Submission status: Accepted

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

#連続する蝋燭を全探索
l=0
r=K-1

ans=2*(10**9)+1
for i in range(N-K+1):
    # print('x[l], x[r]:', x[l], x[r])
    ans = min(ans, min(abs(x[l]), abs(x[r])) + x[r]-x[l])
    l+=1
    r+=1

print(ans)

Submission status: Accepted

Solution code:
import bisect
N, K = [int(i) for i in input().split()]
xs = [int(i) for i in input().split()]

ans = []
bisect.insort_left(xs, 0)
for l in range(len(xs)):
    if l+K < len(xs):
        xl = xs[l]
        xr = xs[l+K]
    elif l-K > -1:
        xl = xs[l-K]
        xr = xs[l]
    else:
        continue

    tmp1 = abs(xl) + abs(xr-xl)
    tmp2 = abs(xr) + abs(xr-xl)
    ans.append(min(tmp1, tmp2))

print(min(ans))

Submission status: Accepted

Solution code:
from math import ceil,floor,comb,factorial,gcd,pow,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n, k = MAP()
x = LIST()

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

print(ans)

Submission status: Accepted

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

K -= 1
D = 10**9
for i in range(N-K):
    d = C[i+K] - C[i]
    L = d + abs(0 - C[i])
    R = d + abs(0 - C[i+K])
    D = min(D,min(L,R))

print(D)

Submission status: Accepted

Solution code:
# coding: utf-8

# https://atcoder.jp/contests/abc107
# 14:34 chudan
# 2020/07/10 retry 12:54-


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

    if xs == [0]:
        return 0

    for i in range(N):
        if xs[i] == 0:
            del xs[i]
            N -= 1
            K -= 1
            break

    if xs[0] > 0:
        xs.insert(0, 0)
        s = 0
    elif xs[N-1] < 0:
        xs.append(0)
        s = N
    else:
        for i in range(N-1):
            if xs[i] < 0 and xs[i+1] > 0:
                xs.insert(i+1, 0)
                s = i+1
                break
    N += 1

    candidates = []
    # from left to right
    if s > K-1:
        l = s-K
        r = s
        d = xs[r] - xs[l]
    else:
        l = 0
        r = K
        d = (xs[s] - xs[l]) + (xs[r] - xs[l])
    candidates.append(d)

    # print(candidates)
    while l < s and r < N-1:
        if r == s:
            d = d - (xs[l+1]-xs[l]) + (xs[r+1]-xs[l+1])
        else:
            d = d - 2*(xs[l+1]-xs[l]) + (xs[r+1]-xs[r])
        candidates.append(d)
        # print(l, r, d)
        l += 1
        r += 1

    # print("="*10)
    # from right to left
    if s+K < N:
        l = s
        r = s+K
        d = xs[r] - xs[l]
    else:
        l = N-(K+1)
        r = N-1
        d = (xs[r]-xs[s]) + (xs[r]-xs[l])
    candidates.append(d)

    # print(candidates)
    while l > 0 and r > s:
        if l == s:
            d = d - (xs[r]-xs[r-1]) + (xs[r-1]-xs[l-1])
        else:
            d = d - 2*(xs[r]-xs[r-1]) + (xs[l]-xs[l-1])
        candidates.append(d)
        # print(l, r, d)
        l -= 1
        r -= 1

    # print(candidates)
    return min(candidates)

    # ds = [None] * N
    # for i in range(N):
    #     ds[i] = xs[i+1]-xs[i]


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

#     if x[-1] <= 0:
#         n_l = N
#         n_r = 0
#         l_start = N-1
#         r_start = None  # all <= 0
#     else:
#         for i in range(N):
#             if x[i] > 0:
#                 n_l = i
#                 n_r = N-i
#                 l_start = i-1 if i > 0 else None  # all > 0
#                 r_start = i
#                 break

#     # left -> right
#     t = []
#     if r_start is None:  # 左に直進するのみ
#         t.append(-x[l_start-K+1])
#     else:
#         n = max(K-n_r, 0)
#         tim = -x[l_start-n+1]*2 + x[K-n]
#         t.append(tim)
#         for n in range(max(K-n_r, 0)+1, n_l+1):
#             tim += 2*(x[l_start-n+1]-x[l_start-n])
#             tim -= x[l_start+K-n]-x[l_start+K-n-1]
#             t.append(tim)

#     # right -> left
#     s = []
#     if l_start is None:  # 右に直進するのみ
#         s.append(x[r_start+K-1])
#     else:
#         m = max(K_n_l, 0)
#         tim = x[r_start+n-1]*2 + 


print(main())

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
X = list(map(int, input().split()))
ans = pow(10,9)+7
for i in range(n-k+1):
    ans = min(ans, min(abs(X[i])+abs(X[i+k-1]-X[i]), abs(X[i+k-1])+abs(X[i]-X[i+k-1])))
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left
n, k = map(int, input().split())
candles = list(map(int, input().split()))
point_zero = bisect_left(candles, 0)
candles.insert(point_zero, 0)
ans = float('inf')
for i in range(min(k, point_zero) + 1):
    left = point_zero - i
    right = point_zero + k - i
    if (0 <= left) and (right < n + 1):
        dis = -candles[left] + candles[right] + min(-candles[left], candles[right])
        ans = min(ans, dis)
print(ans)

Submission status: Accepted

Solution code:
import collections

n,k = map(int, raw_input().split(' '))
xis = map(int, raw_input().split(' '))
ais = [xi for xi in xis if xi >= 0]
bis = [-xi for xi in xis if xi < 0][::-1]
m = ais[k -1] if k-1 < len(ais) else +float('inf')
m = min(m, bis[k -1] if k-1 < len(bis) else +float('inf'))

for i in range(len(ais)):
	if i + 1 == k: break
	if 0 <= k - (i+1) -1 < len(bis):

		m = min(m, 2*ais[i] + bis[k - (i+1) -1])
		m = min(m, ais[i] + 2*bis[k - (i+1) -1])
print m

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, k = map(int, input().split())
    X = list(map(int, input().split()))

    for i in range(n):
        if X[i] >= 0:
            ori = i
            X.insert(ori, 0)
            break
    else:
        ori = n
        X.insert(ori, 0)

    res = f_inf
    start = max(0, ori - k)
    end = min(n - k + 1, ori + 1)
    for j in range(start, end):
        left = abs(X[j]) * 2 + abs(X[j + k])
        right = abs(X[j]) + abs(X[j + k]) * 2
        res = min(res, min(left, right))
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

start = N
for i in range(N):#０より大きい最初のところをstartとする
    if x[i]>0:
        start = i
        break
x.insert(start,0)

ans = float("inf")
for i in range(0,K+1,1):#左側をいくつとるか
    j = K-i#右側はj個とることになる

    if 0 <= start-i and start+j<=N:
        tmpans = x[start+j]-x[start-i]+min(x[start+j],-x[start-i])
        ans = min(ans,tmpans)
print(ans)

Submission status: Accepted

Solution code:
def solve():
    N, K = map(int, input().split())
    x = list(map(int, input().split()))
    ans = 10 ** 13
    for r, l in zip(x[:N - K + 1], x[K - 1:]):
        ans = min(ans, abs(l) + abs(r - l), abs(r) + abs(r - l))

    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
N, K = list(map(int,input().split()))
A = list(map(int,input().split()))
ans = 10 ** 9 + 7
for i in range(N - K + 1):
    left = A[i]
    right = A[i + K - 1]
    if right < 0:  temp = -left
    elif left >= 0:  temp = right
    else:  temp = right - left + min(-left, right)
    ans = min(ans, temp)
print(ans)

Submission status: Accepted

Solution code:
import sys

N, K = map(int, input().split())
X = list(map(int, sys.stdin.readline().rsplit()))

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

print(res)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
x=list(map(int,input().split()))
ans=float("inf")
for i in range(n-k+1):
    l=x[i]
    r=x[i+k-1]
    if l*r==0:
        t=max(abs(l),abs(r))
    if l*r>0:
        t=max(abs(l),abs(r))
    if l*r<0:
        if abs(l)>abs(r):
            t=2*abs(r)+abs(l)
        if abs(r)>=abs(l):
            t=2*abs(l)+abs(r)
    if t<ans:
        ans=t
print(ans)

Submission status: Accepted

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

    ans = 10**9

    for i in range(n-k+1):
        t1 = abs(X[i]) + abs(X[i] - X[i+k-1])
        t2 = abs(X[i+k-1]) + abs(X[i] - X[i+k-1])
        t = min(t1,t2)

        ans = min(ans,t)

    print(ans)



main()

Submission status: Accepted

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

P_list=[0]
N_list=[0]
zero_num=0

for x in X:
    if x < 0:
        N_list.append(-x)
    elif x == 0:
        zero_num=1
    else:
        P_list.append(x)
        
K=K-zero_num

P_list.sort()
N_list.sort()
P_list,N_list

move=[]
for i in range(K+1):
    j=K-i
#     print(i,j)
    if i >= len(P_list) or j >= len(N_list):
        continue
    move_=min(2*P_list[i]+N_list[j],P_list[i]+2*N_list[j])
#     print(move_)
    move.append(move_)
    
if len(move)==0:
    move.append(0)
    
print(min(move))

Submission status: Accepted

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque

# import fractions

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, K = il()
    X = il()

    ret = MAX
    for n in range(N - K + 1):
        ret = min(ret, abs(X[n]) + abs(X[n] - X[n+K-1]), abs(X[n+K-1]) + abs(X[n] - X[n+K-1]))
    print(ret)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from itertools import product

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]


def main():
    N, K = mi()
    x = list(mi())
    m = 10**100
    for i in range(N-K+1):
        tmp = min(abs(x[i]), abs(x[i+K-1]))+(x[i+K-1]-x[i])
        m = min(m, tmp)
    print(m)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

# 連続するK地点を選ぶ
cost = 10**18
for i in range(0, n-k+1):
    left = x[i]
    right = x[i+k-1]
    if left < 0 and right < 0:
        cost = min(cost , abs(left))
    elif left > 0 and right > 0:
        cost = min(cost, abs(right))
    else:
        cost = min(cost, min(2 * abs(right) + abs(left), 2 * abs(left) + abs(right)))

print(cost)

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N, K = LI()
    x = LI()

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

    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
n,k,*a=map(int,open(0).read().split())
ans=10**9
for i in range(n-k+1):
    b,c=a[i],a[i+k-1]
    ans=min(ans,min(abs(b),abs(c))+abs(b-c))
print(ans)

Submission status: Accepted

Solution code:

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

Xrev = X[::-1]
ans = abs(X[0]-X[-1])+abs(X[0])+abs(X[-1])  
for i in range(N-K+1):
    Xdis = abs(X[i])+abs(X[i+K-1]-X[i])
    ans = min(ans,Xdis)
for i in range(N-K+1):
    Xdis = abs(Xrev[i])+abs(Xrev[i+K-1]-Xrev[i])
    ans = min(ans,Xdis)
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):
    left = A[i]
    right = A[i+(k-1)]
    if right <= 0:
        ans = min(ans, abs(left))
    elif 0 <= left:
        ans = min(ans, right)
    else:
        tmp1 = 2*abs(left)+right
        tmp2 = 2*right+abs(left)
        ans = min(ans, min(tmp1, tmp2))
print(ans)

Submission status: Accepted

Solution code:

def solve():
    ans = float("inf")
#    print(x[2])
    for i in range(N-K+1):
        #print(i)
        ans = min(ans, abs(x[i])+abs(x[i]-x[i+K-1]), abs(x[i+K-1])+abs(x[i+K-1]-x[i]))
    print(ans)

if __name__=="__main__":
    N,K = list(map(int, input().split()))
    x = list(map(int, input().split()))
    solve()

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

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():
    N, K = in_nn()
    x = in_nl()

    ans = 10**9 + 7
    for i in range(N - K + 1):
        left = x[i]
        right = x[i + K - 1]
        if right <= 0:
            ans = min(ans, abs(left))
        elif left >= 0:
            ans = min(ans, abs(right))
        else:
            ans = min(ans, abs(left) + abs(right) + min(abs(left), abs(right)))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

print(ans)

Submission status: Accepted

Solution code:
#import numpy as np
import sys, math
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial#, gcd
from bisect import bisect_left #bisect_left(list, value)
sys.setrecursionlimit(10**7)
enu = enumerate
MOD = 10**9+7
def input(): return sys.stdin.readline()[:-1]
pl = lambda x: print(*x, sep='\n')

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

has_zero = 0 in X
negs = [val for val in X if val<0]
poss = [val for val in X if val>0]
lenn = len(negs)
lenp = len(poss)
negs.append(0)
poss = [0] + poss

# print(negs)
# print(poss)

minval = 10**9
if has_zero: K-=1
for left in range(0, K+1):
    right = K-left
    if lenn<left or lenp<right: continue
    # print(left, right)
    negv = abs(negs[lenn-left])
    posv = abs(poss[right])
    val = max(negv, posv) + 2*min(negv, posv)
    if val < minval: minval = val
print(minval)

Submission status: Accepted

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

res = float('inf')
for i in range(n - k + 1):
    if x[i] <= 0 and x[i+k-1] <= 0:
        res = min(res, abs(x[i]))
    elif x[i] <= 0 and x[i+k-1] >= 0:
        res = min(res, 2 * abs(x[i]) + abs(x[i+k-1]), abs(x[i])+ 2 * abs(x[i+k-1]))
    else:
        res = min(res, abs(x[i+k-1]))

print(res)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
x = list(map(int,input().split()))
ans=10**10
for i in range(N+1-K):
 if x[i]>=0 and x[i-1+K]>=0 :
  ans=min(ans,max(x[i],x[i-1+K]))
 elif x[i]<=0 and x[i-1+K]<=0 :
  ans=min(ans,max(-x[i],-x[i-1+K]))
 else:
  ans=min(ans,x[i-1+K]-x[i]+min(x[i-1+K],-x[i]))
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, k = map(int, input().split())
    X = list(map(int, input().split()))

    if X[0] >= 0:
        print(X[k - 1])
        exit()
    elif X[-1] < 0:
        print(abs(X[n - k]))
        exit()
    else:
        for i in range(n):
            if X[i] >= 0:
                ori = i
                break

    res = f_inf
    left = max(ori - k, 0)
    right = min(ori + k, n)
    for i in range(left, right - k + 1):
        RL = abs(X[i + k - 1] - X[i]) + abs(X[i + k - 1])
        LR = abs(X[i]) + abs(X[i + k - 1] - X[i])
        res = min(res, min(RL, LR))
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
x=list(map(int,input().split()))
ans=10**9+7
for i in range(n-k+1):
    temp=x[i+k-1]-x[i]+min(abs(x[i]),abs(x[i+k-1]))
    if temp<ans: ans=temp
print(ans)

Submission status: Accepted

Solution code:
import numpy as np

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

if N == 1:
    print(abs(A[0]))
else:
    distances = np.array([0, *(A[1:] - A[:-1])])
    cumsum = distances.cumsum()
    to_left = abs(A[:-(K - 1)])
    to_right = abs(A[(K - 1):])
    to_start = np.minimum(to_left, to_right)
    to_goal = cumsum[(K - 1):] - cumsum[:-(K - 1)]

    print(min(to_start + to_goal))

Submission status: Accepted

Solution code:
import bisect

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

if 0 not in candles:
    zero_index = bisect.bisect(candles, 0)
else :
    zero_index = candles.index(0)

start_index = max(0, zero_index-K)
end_index = min(start_index+K, N-K+1)

distances = []
for i in range(start_index, end_index):
    if candles[i] < 0 and 0 < candles[i+K-1]:
        dist_left = abs(candles[i])
        dist_right = candles[i+K-1]
        dist = (2 * min(dist_left, dist_right)) + max(dist_left,dist_right)
    else :
        dist = max(abs(candles[i]), abs(candles[i+K-1]))
    distances.append(dist)

print(min(distances))

Submission status: Accepted

Solution code:
import math

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

ans = float('inf')

for i in range(k-1,n):
    bns=min(abs(l[i]-l[i-k+1])+abs(l[i]),abs(l[i]-l[i-k+1])+abs(l[i-k+1]))
    ans=min(ans,bns)
print(ans)

Submission status: Accepted

Solution code:
import bisect

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

x.sort()

if x[-1] <= 0:
  print(abs(x[n-k]))
  exit()
elif x[0] >= 0:
  print(x[k-1])
  exit()

ans = []
if 0 not in x:
  x = [-10**10]*(10**6) + x + [10**10]*(10**6)
  ind = bisect.bisect_left(x,0)
  ans.append(abs(x[ind-k]))
  ans.append(x[ind+k-1])

  for i in range(ind-k+1,ind+k-1):
    a = 2*abs(x[i])+x[i+k-1]
    b = abs(x[i])+2*x[i+k-1]
    ans.append(min(a,b))
    
  print(min(ans))
  
else:
  x = [-10**10]*(10**6) + x + [10**10]*(10**6)
  ind = bisect.bisect_left(x,0)
  ans.append(abs(x[ind-k+1]))
  ans.append(x[ind+k-1])
  
  for i in range(ind-k+2,ind+k-1):
    a = 2*abs(x[i])+x[i+k-1]
    b = abs(x[i])+2*x[i+k-1]
    ans.append(min(a,b))
    
  print(min(ans))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def L(): return list(map(int,input().split()))
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
INF = 10**9
mod = 10**9+7

N,K = I()
x = l()
i = bisect.bisect_left(x,0)
x.insert(i,0)
start = max(i-K,0)
stop = min(i+K+1,N+1)
x = x[start:stop]
ans = 10**9
for i in range(len(x)-K):
    a = x[i]
    b = x[i+K]
    ans = min(ans,min(abs(a),abs(b))+abs(a-b))
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
k -= 1
ans = 10**9

for i in range(n - k):
    l = x[i]
    r = x[i + k]
    if l < 0:
        if r < 0:
            ref = -l
        else:
            ref = min(l*-2 + r, -l + r*2)
    else:
        ref = r
    ans = min(ans, ref)

print(ans)

Submission status: Accepted

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

ans = 10**9

for i in range(n - k + 1):
    if x[i] < 0:
        if x[i + k - 1] < 0:
            ref = -x[i]
        else:
            ref = min(x[i]*-2 + x[i + k - 1], -x[i] + x[i + k - 1]*2)
    else:
        ref = x[i + k - 1]
    ans = min(ans, ref)

print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
a=[int(i) for i in input().split()]
res=100000000000000000000
for i in range(n-k+1):
    l=a[i]
    r=a[i+k-1]
    if l<=0<=r:
        res=min(res,(-l+r)*2-max(-l,r))
    elif r<0:
        res=min(res,-l)
    else:
        res=min(res,r)
print(res)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

md = 20**8 + 1
for l in range(n-k+1):
    r = l+k-1
    md = min(md, abs(x[l]) + abs(x[l] - x[r]))
    md = min(md, abs(x[r]) + abs(x[l] - x[r]))
print(md)

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

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
ans = float("inf")
for i in range(N - K + 1):
    left, right = X[i], X[i + K - 1]
    if left * right <= 0:
        ans = min(ans, abs(left) + right + min(abs(left), right))
    elif left > 0:
        ans = min(ans, right)
    else:
        ans = min(ans, abs(left))
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
start = 0 # i-1本目とi本目の間に0がある

ans = 10**9
for i in range(n-k+1):
    tmp_ans = min(
        abs(x[i]) + abs(x[i+k-1]-x[i]),
        abs(x[i+k-1]) + abs(x[i+k-1]-x[i])
    )
    if tmp_ans < ans:
        ans = tmp_ans

print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
num_list = list(map(int,input().split()))
ans = 10e12
for i in range(n-k+1):
    left = num_list[i]
    right = num_list[i+k-1]
    if (right <= 0) and (left <= 0):
        tmp = abs(left)
    elif (right >= 0) and (left <= 0):
        tmp = min(abs(right) , abs(left)) + abs(right) + abs(left)
    elif (right >= 0) and (left >= 0):
        tmp = abs(right)
    if tmp < ans:
        ans = tmp
print(ans)

Submission status: Accepted

Solution code:
def main():
    n, k = list(map(int, input().split()))
    X = list(map(int, input().split()))
    P = []
    M = []
    for x in X:
        if x >= 0:
            P.append(x)
        else:
            M.append(abs(x))
    m_range = [max(0, k - len(P)), min(len(M), k)]
    p_range = [max(0, k - len(M)), min(len(P), k)]
    P = [0, ] + P
    M = [0, ] + M[::-1]
    ans = float('inf')
    for i in range(m_range[0], m_range[1] + 1):
        ans = min(ans, 2 * M[i] + P[k - i])
    for i in range(p_range[0], p_range[1] + 1):
        ans = min(ans, 2 * P[i] + M[k - i])
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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