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

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

ans = float("INF")
for i in range(N-K+1):
  l = i
  r = i + K - 1
  if X[l] * X[r] < 0:
    ans = min(ans, 2 * min(abs(X[l]), abs(X[r])) + max(abs(X[l]), abs(X[r])))
  else:
    ans = min(ans, abs(X[r]) if X[r] > 0 else abs(X[l]))
print(ans)

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

global_min = float('inf')
for i in range(N-K+1):
    left = i
    right = i+K-1
    

    if 0 <= Xs[left]:
        local_min = Xs[right]
    elif Xs[right] <= 0:
        local_min = abs(Xs[left])
    else: 
        tmp1 = 2 * abs(Xs[left]) + Xs[right]
        tmp2 = abs(Xs[left]) + 2 * Xs[right]
        local_min = min(tmp1, tmp2)

    global_min = min(global_min, local_min)

if global_min == float('inf'):
    print(0)
else:
    print(global_min)

Solution (Python):
def main():
    from sys import setrecursionlimit, stdin
    from os import environ
    from collections import defaultdict, deque, Counter
    
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7

    N,K = LMIIS()
    X = LMIIS()


    
    left = 0
    right = K-1
    syaku = X[right] - X[left]
    if abs(X[left]) > abs(X[right]):
        min_time = syaku + abs(X[right])
    else:
        min_time = syaku + abs(X[left])


    for i in range(N-K+1):
        syaku = X[right] - X[left]
        if abs(X[left]) > abs(X[right]):
            min_time = min(min_time, syaku + abs(X[right]))
        else:
            min_time = min(min_time, syaku + abs(X[left]))
        
        left += 1
        right += 1
    
    print(min_time)



    
main()

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
import copy
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

N, K = getNM()
X = getList()
ans = float('inf')


for i in range(N - K + 1):
    
    
    if X[i] <= 0 and X[i + K - 1] <= 0:
        ans = min(ans, -X[i])
    
    
    
    
    elif X[i] < 0 <= X[i + K - 1]:
        ans = min(ans, min(-X[i], X[i + K - 1]) + (X[i + K - 1] - X[i]))
    
    
    else:
        ans = min(ans, X[i + K - 1])
print(ans)

Solution (Python):
n, k = map(int, input().split())
xlis = list(map(int, input().split()))
ret = 10 ** 100
for i in range(n-k+1):
    min_val = xlis[i]
    max_val = xlis[k+i-1]
    if min_val * max_val >= 0:
        tmp = max(abs(min_val), abs(max_val))
        ret = min(ret, tmp)
    else:
        fst = min(abs(min_val), abs(max_val))
        lst = max(abs(min_val), abs(max_val))
        tmp = fst * 2 + lst
        ret = min(ret, tmp)

print(ret)

Solution (Python):
n, k = map(int, input().split())
xlis = list(map(int, input().split()))
ret = 10 ** 100
for i in range(n-k+1):
    min_val = xlis[i]
    max_val = xlis[k+i-1]
    if min_val * max_val >= 0:
        tmp = max(abs(min_val), abs(max_val))
        ret = min(ret, tmp)
    else:
        fst = min(abs(min_val), abs(max_val))
        lst = max(abs(min_val), abs(max_val))
        tmp = fst * 2 + lst
        ret = min(ret, tmp)

print(ret)

Solution (Python):
def main():
    N, K = list(map(int, input().split(' ')))
    x = list(map(int, input().split(' ')))  
    left = - min([x[0], 0])
    right = max([x[K - 1], 0])
    min_t = min([2 * left + right, left + 2 * right])
    for i in range(N):
        if i + K - 1 > N - 1:
            break
        left = - min([x[i], 0])
        right = max([x[i + K - 1], 0])
        min_t = min([min_t, min([2 * left + right, left + 2 * right])])
    print(min_t)


if __name__ == '__main__':
    main()

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

ans = 10 ** 9

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

print(ans)

Solution (Python):
from bisect import bisect_left

n, k = map(int, input().split())
x = list(map(int, input().split()))
ans = 0
min_dis = 10 ** 20
a = 0
for i in range(n - k + 1):
    dis = x[i + k - 1] - x[i] + min(abs(x[i]), abs(x[i + k - 1]))
    if min_dis > dis:
        ans = dis
        min_dis = dis
print(ans)

Solution (Python):
N, K = map(int, input().split())
l = list(map(int, input().split()))

is_zero = l.count(0)
K -= is_zero

if K:
    ans = float('inf')
    for i in range(N-K+1):
        lb, rb = l[i], l[i+K-1]
        steps = abs(rb-lb) + min(abs(rb), abs(lb))
        ans = min(ans, steps)

    print(ans)
else:
    print(0)

Solution (Python):
import sys

def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))

def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]

def to_bin(x: int) -> str: return format(x, 'b') 
def to_oct(x: int) -> str: return format(x, 'o') 
def to_hex(x: int) -> str: return format(x, 'x') 
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i): is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res

from itertools import accumulate as acc, combinations as combi, product, combinations_with_replacement as combi_dup
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left

def main():
    n, k = MII()
    xx = MII()
    minv = 3*10**8
    for i in range(n-k+1):
        l = xx[i]
        r = xx[i+k-1]
        if l < 0 and r <= 0:
            minv = min(abs(l),minv)
            continue
        if l < 0 and r > 0:
            minv = min(min(abs(l),r)*2+max(abs(l),r), minv)
            continue
        if l >= 0:
            minv = min(r, minv)
            continue
    print(minv)


if __name__ == '__main__':
    main()

Solution (Python):
N, K = map(int, input().split())
X = tuple(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)))

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, k = map(int, readline().split())
x = list(map(int, readline().split()))
p = []
m = [0]
for i, xx in enumerate(x):
    if xx > 0:
        m += x[i:]
        break
    p.append(abs(xx))
p = [0] + p[::-1]
sizep = len(p) - 1
sizem = len(m) - 1
ans = float('inf')
for i in range(k):
    pp = k - i
    mm = i
    if sizep < pp:
        mm += pp - sizep
        pp = sizep
    if sizem < mm:
        pp += mm - sizem
        mm = sizem
    v = p[pp] + m[mm]
    if pp != 0 and mm != 0:
        v += min(p[pp], m[mm])
    ans = min(ans, v)
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline


def readstr():
    return input().strip()


def readint():
    return int(input())


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


def readstrs():
    return input().split()


def main():
    N, K = readnums()
    x = list(readnums())
    ans = 0
    for i in range(K - 1, N):
        ls = i - K + 1
        le = i
        if x[ls] > 0:
            val = abs(x[le])
        elif x[le] < 0:
            val = abs(x[ls])
        else:
            val = abs(x[ls]) + abs(x[le])
            val += min(abs(x[ls]), abs(x[le]))
        if not ans:
            ans = val
        else:
            ans = min(ans, val)

    print(ans)


if __name__ == "__main__":
    main()

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


res=3*10**8+1

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

Solution (Python):
import sys
import bisect
import heapq  


inf = 10 ** 15
mod = 10 ** 9 + 7
n,k = map(int, input().split())
x = list(map(int, input().split()))
minus = []
plus = []
zind = bisect.bisect_left(x, 0)
if zind == n:
    minus = x
    minus.reverse()
else:
    minus = x[0:zind]
    minus.reverse()
    if x[zind] == 0:
        if k == 1:
            print(0)
            sys.exit()
        else:
            n-=1
            k-=1
            plus = x[zind+1:n]
    else:
        plus = x[zind:n]
lenp = len(plus)
lenm = len(minus)
ans = inf
if lenp >= k:
    ans = min(ans, plus[k-1])
if lenm >= k:
    ans = min(ans, abs(minus[k-1]))

for i in range(lenm):
    if 0 <= k-1-(i+1) < lenp:
        ans = min(ans, 2*abs(minus[i])+plus[k-1-(i+1)])
for i in range(lenp):
    if 0 <= k-1-(i+1) < lenm:
        ans = min(ans, 2 * plus[i] + abs(minus[k-1-(i+1)]))

print(ans)

Solution (Python):

import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
X = lr()
answer = []
for i in range(N-K+1):
    l = X[i]; r = X[i+K-1]
    a = abs(l) + abs(r-l)
    b = abs(r) + abs(l-r)
    answer.append(min(a, b))

print(min(answer))

Solution (Python):

import sys
from bisect import bisect_left, bisect_right

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
X = lr()
if 0 in X:
    K -= 1

i = bisect_left(X, 0)
ne = X[:i]
i = bisect_right(X, 0)
po = X[i:]
INF = 10 ** 10
neg = [INF] * (K+1)  
neg[-1] = 0
pos = [INF] * (K+1)
pos[0] = 0
for j in range(len(ne)):
    if -j-2 < -K-1:
        break
    neg[-j-2] = ne[-j-1]

for j in range(len(po)):
    if j+1 > K:
        break
    pos[j+1] = po[j]

answer = INF
for j in range(K+1):
    x = abs(neg[j]); y = abs(pos[j])
    mi = min(x, y)
    ma = max(x, y)
    temp = mi * 2 + ma
    if temp < answer:
        answer = temp
print(answer)

Solution (Python):
n, k = map(int, input().split())
data = list(map(int, input().split()))
l = 0
r = k - 1
ans = float("inf")
while True:
    if r == n:
        break
    ans = min(ans, abs(data[l]) + abs(data[l] - data[r]), abs(data[r]) + abs(data[r] - data[l]))
    l += 1
    r += 1
print(ans)

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

Solution (Python):
n , k  = map(int,input().split())
x = list(map(int,input().split()))
ans = 10**9 
for i in range(n-k+1):
    l = x[i]
    r = x[i+k-1]
    if l*r >= 0:
        ans = min(ans,max(abs(r),abs(l)))
    elif l*r < 0:
        ans = min(ans,r-l + min(abs(r),abs(l)))
print(ans)

Solution (Python):
cand_num, tenka = map(int, input().split(" "))
candles = list(map(int, input().split(" ")))
mini = 10 ** 9

for i in range(cand_num - tenka + 1):
    if candles[i] * candles[tenka + i - 1] >= 0:
        temp = max(abs(candles[i]), abs(candles[tenka + i - 1]))
    else:
        temp = min(abs(candles[i]), abs(candles[tenka + i- 1])) * 2 + max(abs(candles[i]), abs(candles[tenka + i - 1]))
    mini = temp if mini > temp else mini
print(mini)

Solution (Python):
n, k, *a = map(int, open(0).read().split())
m = INF = float("inf")
for i in range(n - k + 1):
    l, r = a[i], a[i + k - 1]
    c = abs(r-l)
    m = min(m, min(abs(l) + c, abs(r) + c))
print(m)

Solution (Python):
n, k = map(int, input().split())
x = list(map(int, input().split()))
ans = 10**10
for i in range(n - k + 1):
  ans = min(ans, max(0, -x[i]) + max(0, 2 * x[i + k - 1]),
            max(0, -2 * x[i]) + max(0, x[i + k - 1]))
print(ans)

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

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

X_n = sorted([-x for x in X if x < 0])
X_p = sorted([x for x in X if x >= 0])

ans = 10**20
for k in range(K+1):
    if len(X_n) >= k and len(X_p) >= K-k:
        if k == 0:
            ans = min(ans, X_p[K-1])
        elif k == K:
            ans = min(ans, X_n[K-1])
        else:
            ans = min(ans, 2*X_n[k-1] + X_p[K-k-1], X_n[k-1] + 2*X_p[K-k-1])
print(ans)

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





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

Solution (Python):


import sys






















def main():
    mod = 1000000007                
    inf = float('inf')              
    
    sys.setrecursionlimit(10**6)    
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, k = mi()
    L = lmi()
    ans = 2 ** 64 - 1
    for i in range(n - (k - 1)):
        if L[i+k-1] <= 0:
            cost = abs(L[i])
        elif L[i] >= 0:
            cost = L[i+k-1]
        else:
            cost = L[i+k-1] - L[i] + min(abs(L[i]), L[i+k-1])
        ans = min(ans, cost)
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
import sys
def input(): return sys.stdin.readline().rstrip()
from bisect import bisect
def main():
    n,k=map(int,input().split())
    X=list(map(int,input().split()))
    zero=bisect(X,0)
    ans=10**9
    for i in range(k+1):
        if zero-i<0 or zero+k-i-1>=n:
            continue
        if i==0:
            ans=min(ans,X[zero+k-i-1])
        elif i==k:
            ans=min(ans,-X[zero-i])
        else:
            kyori_m=2*-X[zero-i]+X[zero+k-i-1]
            kyori_p=-X[zero-i]+2*X[zero+k-i-1]
            ans=min(ans,kyori_m,kyori_p)  
    print(ans)

if __name__=='__main__':
    main()

Solution (Python):
import sys
def input(): return sys.stdin.readline().rstrip()
from bisect import bisect
def main():
    n,k=map(int,input().split())
    X=list(map(int,input().split()))
    zero=bisect(X,0)
    ans=10**9
    for i in range(k+1):
        if zero-i<0 or zero+k-i-1>=n:
            continue
        if i==0:
            ans=min(ans,X[zero+k-i-1])
        elif i==k:
            ans=min(ans,-X[zero-i])
        else:
            kyori_m=2*-X[zero-i]+X[zero+k-i-1]
            kyori_p=-X[zero-i]+2*X[zero+k-i-1]
            ans=min(ans,kyori_m,kyori_p)  
    print(ans)

if __name__=='__main__':
    main()

Solution (Python):
N,K=map(int,input().split())
X=list(map(int,input().split()))
import numpy as np
a=np.searchsorted(X, 0, side='left')
if a==N:
  X=np.insert(X,a,0)
  N+=1
  K+=1
elif X[a]!=0:
  X=np.insert(X,a,0)
  N+=1
  K+=1
ans=10**18
i=a-K+1 if K-1<a else 0
while i<=a and i+K-1<N:
  l=-X[i]
  r=X[i+K-1]
  if l>r:
    l,r=r,l
  ans=min(ans,2*l+r)
  i+=1
print(ans)

Solution (Python):
from bisect import bisect_left

n, k = [int(i) for i in input().split()]
x_list = [int(i) for i in input().split()]

ans = 10 ** 9
i = bisect_left(x_list, 0)
for j in range(max(i - k, 0), min(i + 1, n - k + 1)):
    if j == i - k:
        temp = abs(x_list[j])
    elif j == i:
        temp = x_list[j + k - 1]
    else:
        temp = x_list[j + k - 1] - x_list[j] + min(-x_list[j], x_list[j + k - 1])
    
    if temp < ans:
        ans = temp
print(ans)

Solution (Python):
N, K = map(int, input().split())
X = list(map(int, input().split()))
check_X = X[0:K]

def calc_distance(check_X):
    if check_X[0] * check_X[-1] < 0:
        result = min(abs(check_X[0]*2)+abs(check_X[-1]), abs(check_X[0])+abs(check_X[-1]*2))
    else:
        result = max(abs(check_X[0]),abs(check_X[-1]))
    return result

ans = calc_distance(check_X)

for i in range(K, len(X)):
    check_X.pop(0)
    check_X.append(X[i])
    ans = min(ans, calc_distance(check_X))

print(ans)

Solution (Python):
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)


class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True




def warshall_floyd(d, n):
    
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d



def dijkstra_heap(s, edge, n):
    
    d = [10**20] * n
    used = [True] * n 
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d


def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr


def lcm(x, y):
    return (x * y) // gcd(x, y)


def lcm_list(numbers):
    return reduce(lcm, numbers, 1)


def gcd_list(numbers):
    return reduce(gcd, numbers)






def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P


def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret



n, k = map(int, input().split())
x = list(map(int, input().split()))
a = []
b = []
ans = INF
for i in x:
    if i < 0:
        a.append(- i)
    elif i == 0:
        k -= 1
    else:
        b.append(i)
a = a[::-1]


for i in range(k + 1):
    if i > len(a) or k - i > len(b):
        continue
    cnt1 = 0
    cnt2 = 0
    if i != 0:
        cnt1 = a[i - 1]
    if i != k:
        cnt2 = b[k - i - 1]
    total = min(cnt1, cnt2) * 2 + max(cnt1, cnt2)
    
    ans = min(ans, total)
print(ans)

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

ptns = []
for i in range(n-k+1):
    ptns.append(abs(0 -l[i]) + abs(l[i] - l[i+k-1]))
    ptns.append(abs(0 -l[i+k-1]) + abs(l[i+k-1] - l[i]))

print(min(ptns))

Solution (Python):


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

nums = [int(i) for i in input().split()]

ans = float('inf')
for i in range(n - k + 1):
    l = nums[i]
    r = nums[i + k - 1]
    if l >= 0:
        t = r
    elif r <= 0:
        t = abs(l)
    else:
        t = min(abs(l), abs(r)) * 2 + max(abs(l), abs(r))
    ans = min(ans, t)

print(ans)

Solution (Python):
N,K = map(int,input().split())
x = list(map(int,input().split()))
INF = 3*10**8+1

x_plus,x_minus,x_zero = [],[],0
for i in range(N):
    if x[i] < 0:
        x_minus.append(x[i])
    elif x[i] == 0:
        x_zero += 1
    else:
        x_plus.append(x[i])
for i in range(len(x_minus)//2):
    x_minus[i],x_minus[len(x_minus)-i-1] = x_minus[len(x_minus)-i-1],x_minus[i]

ans = INF
if 0 <= K-1-x_zero and K-1-x_zero < len(x_plus):
    ans = min(ans,x_plus[K-1-x_zero])
if 0 <= K-1-x_zero and K-1-x_zero < len(x_minus):
    ans = min(ans,-x_minus[K-1-x_zero])
for i in range(K):
    if i < len(x_plus) and 0 <= K-i-2-x_zero and K-i-2-x_zero < len(x_minus):
        tmp1 = 2*x_plus[i]-x_minus[K-i-2-x_zero]
        tmp2 = x_plus[i]-2*x_minus[K-i-2-x_zero]
        ans = min(ans,tmp1,tmp2)
if ans == INF:
    ans = 0
print(ans)

Solution (Python):
n,k = map(int,input().split())
x = list(map(int,input().split()))
flag = True
for i in range(n+1):
    if i == n or x[i] > 0:
        x.insert(i,0)
        zahyou = i
        break
ans = 10**18
for i in range(k+1):
    flag = True
    if zahyou + i < n+1 and zahyou -k+i >= 0:
        mainasu = x[zahyou]-x[zahyou-k+i]
        purasu = x[zahyou+i]-x[zahyou]
        if mainasu != 0 and purasu != 0:
            purasu += min(mainasu,purasu)
        ans = min(ans,mainasu+purasu)
print(ans)

Solution (Python):
def main():
  import bisect
  n,k=map(int,input().split())
  x=list(map(int,input().split()))
  ans=abs(x[0])*2+abs(x[-1])*2
  if 0 in x:
    r=x.index(0)
    l=max(0,r-(k-1))
  else:
    r=bisect.bisect_right(x,0)
    l=max(0,r-k)
  ans=2*abs(x[0])+2*abs(x[-1])
  for i in range(l,min(n-k+1,r+1)):
    if x[i]*x[i+k-1]<=0:
      a=min(abs(x[i]),abs(x[i+k-1]))
      b=max(abs(x[i]),abs(x[i+k-1]))
      ans=min(ans,2*a+b)
    else:
      b=max(abs(x[i]),abs(x[i+k-1]))
      ans=min(ans,b)
  print(ans)
if __name__=='__main__':
  main()

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

minus = []
plus = []

for x in X:
    if x < 0:
        minus.append(-x)
    else:
        plus.append(x)

minus.reverse()
ans = float('inf')


for i in range(min(K+1, len(minus)+1)):
    p = K - i
    if i == 0:
        if len(plus) >= p:
            ans = min(ans, plus[K-1])
    elif i == K:
        if len(minus) >= K:
            ans = min(ans, minus[K-1])
    else:
        if len(plus) >= p and len(minus) >= i:
            a = plus[p-1]
            b = minus[i-1]
            if a < b:
                ans = min(ans, 2 * a + b)
            else:
                ans = min(ans, b * 2 + a)

print(ans)

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

ans = float("inf")

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

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

for i in range(n-k+1):
    st=x[i]
    ed=x[i+k-1]
    
    if ed<=0:
        ans=min(ans,abs(st))
    elif st>=0 and ed>=0:
        ans=min(ans,ed)
    else:
        t=(min(abs(st),ed)*2)+max(abs(st),ed)
        ans=min(t,ans)

print(ans)

Solution (Python):
import bisect
n,k = map(int,input().split())
x = list(map(int,input().split()))
zero = bisect.bisect(x,0)
left = [0] + (x[:zero])[::-1]
right = [0] + x[zero:]
ans = 10**12
for i in range(min(k+1,len(left))):
  j = k-i
  if j >= len(right):
    continue
  ans = min(ans,2*right[j]-left[i],-2*left[i]+right[j])
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 7)
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):
    left = x[i]
    right = x[i+k-1]
    if left <= 0 <= right:
        tmp = -(left) + right
        tmp += min(-left,right)
        ans = min(ans,tmp)
    elif 0 < left:
        ans = min(ans,right)
    elif right < 0:
        ans = min(ans,abs(left))

print(ans)

Solution (Python):
import bisect
n,k = map(int, input().split())
x = list(map(int, input().split()))
z = bisect.bisect_left(x,0)

ans=10**12
s=z-k
if s < 0:
  s=0
g=z+1
if g+k >= n:
  g=n-k+1
for i in range(s,g):

  xl=x[i]
  xr=x[i+k-1]
  ans=min(ans,abs(xr)+abs(xr-xl),abs(xl)+abs(xr-xl))
print(ans)

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

Solution (Python):
n,k = map(int,input().split())
li = list(map(int,input().split()))

if k == 1:
    print(min(abs(max(li)),abs(min(li))))
    exit()

time_li = []
for i in range(n-k+1):
    
    tmp_time_li = []
    mi = li[i]
    ma = li[i+k-1]
    if mi > 0 and ma >0:
        tmp_time_li.append(ma)
    elif mi < 0 and ma < 0:
        tmp_time_li.append(abs(mi))
    else:
        orikaeshi = min(abs(mi),abs(ma))*2+max(abs(mi),abs(ma))
        tmp_time_li.append(orikaeshi)
    time_li.append(tmp_time_li[0])
print(min(time_li))

Solution (Python):
from bisect import bisect_right, bisect_left

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

ans = 4*10**8 + 1
x_0 = bisect_right(x, 0)
x_1 = bisect_left(x, 0) - 1

for i in range(N-K+1):
    if i + K -1 >= x_1 and i <= x_0:
        if x[i + K - 1] <= 0:
            ans = min(ans, -x[i])
        elif x[i] >= 0:
            ans = min(ans, x[i + K - 1])
        else:
            ans = min(ans, min(-x[i]*2 + x[i+K-1], -x[i] + x[i+K-1]*2))
print(ans)

Solution (Python):



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


ans = float('INF')
loop_count = N - K + 1


if N-K==0:
    loop_count = 1
for i in range(loop_count):
    f = x_nums[i]
    l = x_nums[i+K-1]
    if f<0:
        if l>=0:
            tmp_time_1 = abs(f)*2 + abs(l)
            tmp_time_2 = abs(l)*2 + abs(f)
            tmp_time = min(tmp_time_1, tmp_time_2)
            ans = min(ans, tmp_time)
        else:
            ans = min(ans, abs(f))
    else:
        ans = min(ans, abs(l))


print(ans)

Solution (Python):
n,k=map(int,input().split())
x=list(map(int,input().split()))
xp=[xi for xi in x if xi>=0]
xm=[xi for xi in x if xi<0]
xm.sort(reverse=True)
ans=3*10**8
for i in range(k+1):
    
    if i>len(xp) or k-i>len(xm):
        continue
    a=xp[i-1] if len(xp)>0 and i>0 else 0
    b=xm[k-i-1] if len(xm)>0 and k-i>0 else 0
    ans=min(ans,2*a-b,a-2*b)
print(ans)

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

int1 = lambda x: int(x) - 1
def II(): return int(input())

def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())

def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

INF = float('inf')

def solve():
    n, k = MI()
    X = LI()


    ans = INF
    for i in range(n + 1 - k):
        xl = X[i]
        xr = X[i+(k-1)]

        d_l = abs(xl)
        d_r = abs(xr)
        d_d = abs(xl - xr)
        ans = min(ans, min(d_l + d_d, d_r + d_d))
    print(ans)


if __name__ == '__main__':
    solve()

Solution (Python):
from bisect import bisect_left, bisect_right

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

X = list(map(int, input().split()))
Ne = bisect_left(X, 0)
Po = bisect_right(X, 0)

if Ne != Po:
  K -= 1

ans = 10**9

for i in range(K+1):
  tmp = 10**9
  if i > N - Po:
    continue
  if K - i > Ne:
    continue
  
  if i == 0:
    tmp = abs(X[Ne-K])
  
  elif i == K:
    tmp = abs(X[Po+K-1])
  
  else:
    tmp = X[Po+i-1] - X[Ne-(K-i)] + min(abs(X[Po+i-1]),abs(X[Ne-(K-i)])) 

  ans = min(ans,tmp)

print(ans)

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

xmin=(x[n-1]-x[0])*2

for i in range(n-k+1):
    x1=abs(x[i])+abs(x[i+k-1]-x[i])
    x2=abs(x[i+k-1])+abs(x[i+k-1]-x[i])
    xmin=min(xmin,x1,x2)

print(xmin)

Solution (Python):
n, k = map(int,input().split())
x = list(map(int,input().split()))
ans = 10 ** 9
for l in range(n - k + 1):
    dist = abs(x[l] - x[l + k - 1])
    dist += min(abs(x[l]), abs(x[l+k-1]))
    ans = min(ans,dist)
print(ans)