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:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


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


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, K, X):

    ans = sys.maxsize
    for i in range(N-K+1):
        c = 0
        if X[i] <= 0 and X[i+K-1] <= 0:
            c += -X[i]
        elif X[i] <= 0 and X[i+K-1] > 0:
            c += -2*X[i] + X[i+K-1]
        else:
            c += X[i+K-1]

        # print(c)
        ans = min(ans, c)

    X = [-x for x in reversed(X)]
    for i in range(N-K+1):
        c = 0
        if X[i] <= 0 and X[i+K-1] <= 0:
            c += -X[i]
        elif X[i] <= 0 and X[i+K-1] > 0:
            c += -2*X[i] + X[i+K-1]
        else:
            c += X[i+K-1]

        # print(c)
        ans = min(ans, c)
    return ans


def main():
    N, K = read_int_n()
    X = read_int_n()
    print(slv(N, K, X))


if __name__ == '__main__':
    main()

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] >= 0 and x[i+K-1] >= 0:
        ans = min(ans,x[i+K-1])
    elif x[i] < 0 and x[i+K-1] < 0:
        ans = min(ans,-x[i])
    else:
        l = -x[i]
        r = x[i+K-1]
        mi = min(l,r)
        mx = max(l,r)
        ans = min(ans,mi*2+mx)

print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
X = list(map(int,input().split()))
x_n = [0] + sorted([-x for x in X if x < 0])
x_p = [0] + sorted([x for x in X if x >= 0])
size_n,size_p = len(x_n), len(x_p)
ans = 2 * 10**10
for i in range(K+1):
	if i < size_n and K-i < size_p:
		ans = min(ans, x_n[i] + x_p[K-i] + min(x_n[i], x_p[K-i]))
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int, input().split())
a=list(map(int, input().split()))
a2=[i for i in a if i>=0]
b=sorted([-1*i for i in a])
b2=[i for i in b if i>=0]
ans=10**9
for i in range(n-k+1):
    if a[i]>=0:ans=min(ans,a2[k-1])
    else:
        ans=min(ans,a[k+i-1]-a[i]*2)
for i in range(n-k+1):
    if b[i]>=0:ans=min(ans,b2[k-1])
    else:
        ans=min(ans,b[k+i-1]-b[i]*2) 
print(ans)

Submission status: Accepted

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

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

d=0
#print(x)

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



print(ans)

Submission status: Accepted

Solution code:
import sys,collections,math;sys.setrecursionlimit(10**7)
def Is(): return [int(x) for x in sys.stdin.readline().split()]
def Ss(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

n,k = Is()
xs = Is()
c = []
for i in range(n-k+1):
    L,R = xs[i], xs[i+k-1]
    if L < 0 and R >= 0:
        c.append(-L + R + min(-L,R))
    else:
        c.append(max(abs(L),abs(R)))
        
print(min(c))

Submission status: Accepted

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

l1 = []
l2 = []
for i in range(N):
    if x[i] == 0:
        K -= 1
    elif x[i] > 0:
        l1.append(x[i])
    else:
        l2.append(-x[i])

l2.sort()

ans = 10**9
if K == 0:
    ans = 0
else:
    if K <= len(l1):
        ans = min(ans, l1[K-1])
    if K <= len(l2):
        ans = min(ans, l2[K-1])

for i in range(max(1, K-len(l1)), min(K, len(l2)+1)):
    ans = min(ans, l1[K-1-i]+l2[i-1]*2, l1[K-1-i]*2+l2[i-1])

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from bisect import bisect_left
s=input().split()
n,k=int(s[0]),int(s[1])
s=input().split()
l=[int(s[i]) for i in range(n)]
if min(l)>=0:
    print(l[k-1])
elif max(l)<=0:
    print(-l[-k])
else:
    ind=bisect_left(l,0)
    if l[ind]==0:
        k-=1
        del(l[ind])
    costr=[0]+l[ind:]
    lef=l[:ind]
    costl=[0]+[-lef[-i] for i in range(1,1+len(lef))]
    if k==0:
        print(0)
    else:
        res=10000000000000000000
        for i in range(len(costr)):
            if i>k:
                break
            nowcost=costr[i]*2
            if k-i<len(costl):
                res=min(res,nowcost+costl[k-i])
        for i in range(len(costl)):
            if i>k:
                break
            nowcost=costl[i]*2
            if k-i<len(costr):
                res=min(res,nowcost+costr[k-i])
        print(res)

Submission status: Accepted

Solution code:
import bisect


def main():
    n, k = map(int, raw_input().split())
    xx = map(int, raw_input().split())
    yy = [0]
    for i in range(1, n):
        yy.append(yy[-1] + xx[i] - xx[i - 1])

    ori = bisect.bisect_left(xx, 0)
    best = float('inf')
    for i in xrange(max(0, ori - k), min(n - k + 1, ori + 1)):
        dest = yy[i + k - 1] - yy[i] + min(abs(xx[i]), abs(xx[i + k - 1]))
        best = min(dest, best)
    print(best)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

ns = [-v for v in vs if v < 0][::-1]
ps = [v for v in vs if v >= 0]

res = float('inf')
if len(ps) >= k:
    res = ps[k-1]
for i in range(min(k, len(ns))):
    if len(ps) + i + 1 < k: continue
    res = min(res, ns[i] * 2 + (ps[k - i - 2] if k > i + 1 else 0))
    res = min(res, ns[i] + (ps[k - i - 2] if k > i + 1 else 0) * 2)

print(res)

Submission status: Accepted

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

pos = []
neg = []
for x in X:
  if x >= 0:
    pos.append(x)
  else:
    neg.append(-x)

plen = len(pos)
nlen = len(neg)
pos = [0] + sorted(pos)
neg = [0] + sorted(neg)
ans = float('inf')
for p in range(min(K + 1, plen + 1)): # pos方向にいくつ進むか
  if p + nlen < K:
    continue
  pcost = pos[p]
  ncost = neg[K - p]
  if pcost * ncost == 0:
    ans = ans if ans < pcost + ncost else pcost + ncost
  else:
    t1 = pcost * 2 + ncost
    t2 = ncost * 2 + pcost
    ans = ans if ans < t1 else t1
    ans = ans if ans < t2 else t2

print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
x=[int(i) for i in input().split()]
ans=10**9
A=[]
B=[]
for i in range(N):
    if x[i]>=0:
        A.append(x[i])
    else:
        B.append(-x[i])
B=B[::-1]
if len(A)>=K:
    ans=min([ans,A[K-1]])
if len(B)>=K:
    ans=min([ans,B[K-1]])
C=len(A)
D=len(B)
for i in range(1,K):
    if ((i-1)<C) and ((K-i-1)<D):
        tmp1=A[i-1]+2*B[K-i-1]
        tmp2=2*A[i-1]+B[K-i-1]
        ans=min([ans,tmp1,tmp2])
print(ans)

Submission status: Accepted

Solution code:
# S = input()
# N = int(input())
N, K = map(int, input().split())
X = list(map(int, input().split()))
# LR = [list(map(int, input().split())) for _ in range(M)]

ans = 10000000000

if K == 1:
    for i in range(N):
        if ans > abs(X[i]):
            ans = abs(X[i])
else:
    for i in range(N - K+1):
        left = X[i]
        right = X[i + K - 1]
        sum = 0

        if abs(left) <= abs(right):
            sum += abs(left)
        else:
            sum += abs(right)

        sum += abs(left - right)

        if ans > sum:
            ans = sum

print(ans)

Submission status: Accepted

Solution code:
import bisect


def solve(n, k, xxx):
    i0 = bisect.bisect(xxx, 0)
    if i0 == 0:
        return xxx[k - 1]
    if i0 == n:
        return -xxx[-k]

    xxx.insert(i0, 0)
    # print(xxx)
    ans = float('inf')
    for p in range(k + 1):
        li = i0 - k + p
        ri = i0 + p
        # print(p, li, ri, -xxx[li] * 2 + xxx[ri], -xxx[li] + xxx[ri] * 2)
        if li < 0 or ri > n:
            continue
        ans = min(ans, -xxx[li] * 2 + xxx[ri], -xxx[li] + xxx[ri] * 2)
    return ans


n, k = map(int, input().split())
xxx = list(map(int, input().split()))
print(solve(n, k, xxx))

Submission status: Accepted

Solution code:
N, K = map(int,input().split())
x=[int(i) for i in input().split()]
m=9999999999
for i in range(0,N-K+1):
    if x[i+K-1]<=0:
        if -x[i]<m:
            m=-x[i]
    elif x[i]>=0:
        if x[i+K-1]<m:
            m=x[i+K-1]
    elif x[i+K-1]>-x[i]:
        if -2*x[i]+x[i+K-1]<m:
            m=-2*x[i]+x[i+K-1]
    else:
        if 2*x[i+K-1]-x[i]<m:
            m=2*x[i+K-1]-x[i]
print(m)

Submission status: Accepted

Solution code:
import sys
N,K = map(int,raw_input().split())
nums = list(map(int,raw_input().split()))
f = 0
f2 = 0
for i in range(N):
    if nums[i]<0:
        f = 1
    if nums[i]>0:
        f2 = 1
if not f or not f2:
    if nums[0]<0:
        print -nums[N-K]
    else:
        print nums[K-1]
    sys.exit()
ans = pow(10,15)
for i in range(N-1):
    if nums[i]<0 and nums[i+1]>=0:
        cnt = 0
        l = i
        r = i
        for j in range(i,-1,-1):
            cnt += 1
            if cnt==K or l==0:
                break
            l -= 1
        for j in range(i+1,N):
            if cnt==K or r==N-1:
                break
            cnt += 1
            r += 1
        for j in range(K):
            if l>i or r>N-1:
                break
            cur = nums[l]
            cur2 = nums[r]
            l += 1
            r += 1
            if cur>=0:
                break
            ans = min(ans,abs(cur*2)+cur2,abs(cur)+cur2*2)
print ans

Submission status: Accepted

Solution code:
n, k = map(int,input().split())
xs = list(map(int,input().split()))
ans = 1000000000000
if n == 1:
    print(xs[0])
    quit()
if k == 1:
    print(min(list(map(abs,xs))))
    quit()
for i in range(n-k+1):
    a,b = xs[i],xs[i+k-1]
    if b <= 0:
        if ans > (-1 * a):
            ans = (-1 * a)
    elif a >= 0:
        if ans > b:
            ans = b
    else:
        if min(b * 2 - a , b - 2 * a) < ans:
            ans = min(b * 2 - a , b - 2 * a)
print(ans)

Submission status: Accepted

Solution code:
import bisect
import numpy


N,K=[ int(x) for x in raw_input().split() ]
X=[ int(x) for x in raw_input().split() ]
zl=bisect.bisect(X, 0)

XL=[0]+sorted([ -x for x in X[:zl] ])
XR=[0]+X[zl:]

SL= XL
SR= XR
ans=1e20

for m in range(K+1):
    try:
        anstmp = SL[m]+SR[K-m] + min(SL[m], SR[K-m] )
        ans=min(ans, anstmp)
    except:
        pass
print int(ans)

Submission status: Accepted

Solution code:
# coding: utf-8

def main():
    N, K = map(int, input().split(" "))
    xp = []
    xm = []
    for x in map(int, input().split(" ")):
        if x > 0:
            xp.append(x)
        elif x < 0:
            xm.append(-x)
        else:
            K -= 1
    if K <= 0:
        return 0
    xm.sort()

    ans = float("inf")
    kp = min(len(xp), K)
    while kp >= 0:
        km = K - kp
        if kp == 0 and len(xm) >= km:
            ans = min(ans, xm[km-1])
        elif km == 0:
            ans = min(ans, xp[kp-1])
        elif len(xm) >= km:
            ans = min(ans, xp[kp-1] * 2 + xm[km-1], xp[kp-1] + xm[km-1] * 2)
        kp -= 1
    return ans

if __name__ == "__main__":
    print(main())

Submission status: Accepted

Solution code:
import sys
n,k = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
ma = []
pu = []
for i in range(n):
    if a[i] < 0:
        ma.append(a[i])
    else:
        pu.append(a[i])
for i in range(len(ma)):
    ma[i] = -ma[i]
ma.sort()
ans = float("inf")
for i in range(len(ma)):
    kota = 0
    kota += ma[i]
    if k <= i+1:
        ans = min(kota,ans)
    else:
        kota += ma[i]
        if len(pu) >= k- i-1:
            kota += pu[k-i-2]
            ans = min(kota,ans)
for i in range(len(pu)):
    kota = 0
    kota += pu[i]
    if k <= i+1:
        ans = min(kota,ans)
    else:
        kota += pu[i]
        if len(ma) >= k- i-1:
            kota += ma[k-i-2]
            ans = min(kota,ans)
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
x=list(map(int,input().split()))
index = 0
ans = 10**9
while index + K - 1 < N:
    start = x[index]
    end = x[index + K - 1]
    if start < 0:
        ans = min(ans,abs(end-start)+abs(start))
        ans = min(ans,abs(end-start)+abs(end))
    else:
        ans = min(ans,end)
    index += 1
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq

# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
# MOD = 10**9 + 7

def solve(f):
    n, k = f.read_int_list()
    x = f.read_int_list()

    ans = float('inf')

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


    return ans


class Reader(object):
    def __init__(self, filename=None):
        self.file = open(filename) if filename is not None else None
        self.case = 1

    def __readline(self):
        return self.file.next().strip() if self.file else raw_input()

    def next_case(self):
        self.file.next()
        self.case += 1

    def read_int(self): return int(self.__readline())
    def read_float(self): return float(self.__readline())
    def read_long(self): return long(self.__readline())
    def read_decimal(self): return decimal.Decimal(self.__readline())
    def read_str(self): return self.__readline()

    def read_int_list(self): return map(int, self.__readline().split())
    def read_float_list(self): return map(float, self.__readline().split())
    def read_long_list(self): return map(long, self.__readline().split())
    def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split())
    def read_str_list(self): return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv) > 1 else None
    f = Reader(filename)
    if f.file:
        while True:
            print "Case #%d\n"%f.case, solve(f)
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
try: from typing import Any, Union, List, Tuple, Dict
except ImportError: pass
sys.setrecursionlimit(10**6)
def debug(*args): print(*args, file=sys.stderr)
def exit(): sys.exit(0)


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


# s = [0]  # type: List[int]
# sum_ = 0
# for i in range(N):
#     sum_ += x[i]
#     s.append(sum_)
def abs(n):
    if n >= 0:
        return n
    else:
        return -n
times = []                      # type: List[int]
for i in range(N-K+1):
    t = x[i+K-1] - x[i]
    t += min(abs(x[i+K-1]), abs(x[i]))
    times.append(t)

debug(times)
print(min(times))

Submission status: Accepted

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

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

left = []
right = []

for x in X:
    if x<0:
        left.append(-x)
    if x==0:
        K-=1
    if x>0:
        right.append(x)
left = list(reversed(left))
left.insert(0,0)
right.insert(0,0)

def solve(left,right):
    result = float('inf')
    for i in range(min(len(left),K)):
        #print(i,left,right)
        tmp_time =  2*left[i]
        tmp_count = i
        if i + len(right)-1 < K:
            continue
        tmp_result = tmp_time+ right[K-i]
        result  = min(result,tmp_result)

    return result


if K==0 :
    print(0)
    exit()
print(min(solve(left,right),solve(right,left)))

Submission status: Accepted

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


ans = 1000000000000000000000000000
for l in range(n):
    r = l+k-1
    if r >= n:
        break
    if x[r]*x[l]<0:
        ans = min(ans,min(abs(x[l]),abs(x[r]))*2+max(abs(x[l]),abs(x[r])))
    else:
        ans = min(ans,max(abs(x[l]),x[r]))

print(ans)

Submission status: Accepted

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

result = []
for i in range(n - k + 1):
    left = x[i]
    right = x[i + k - 1]
    if left < 0:
        if right < 0:
            result.append(- left)
        else:
            if left + right < 0:
                result.append(- left + 2 * right)
            else:
                result.append(-2 * left + right)
    else:
        result.append(right)
print(min(result))

Submission status: Accepted

Solution code:
# encoding:utf-8
def main():
	n, k = list(map(int, input().split()))
	xs = list(map(int, input().split()))
	
	min_dist = 10 ** 10
	for i in range(n - k + 1):
		dist = min(abs(xs[i]), abs(xs[i + k - 1])) + (xs[i + k - 1] - xs[i])
		if dist <= min_dist:
			min_dist = dist
	print(min_dist)


if __name__ == '__main__':
	main()

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

Submission status: Accepted

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

result = 10 ** 20

for i in range(N - K + 1):
    a, b = X[i], X[i + K - 1]
    dmax = max(abs(a), abs(b))
    dmin = min(abs(a), abs(b))
    if a * b >= 0:
        r = dmax
    else:
        r = dmax + dmin * 2
    result = min(result, r)

print(result)

Submission status: Accepted

Solution code:
def solve(N, K, x):
  ans = 10**20
  for i in range(N-K+1):
    if x[i]>=0:
      ans = min(ans, x[i+K-1])
    elif x[i+K-1]>0:
      ans = min(ans, -x[i]*2+x[i+K-1])
    else:
      ans = min(ans, -x[i])
  return ans

N,K = map(int, raw_input().split())
x = map(int, raw_input().split())
print min(solve(N,K,x), solve(N,K,[-t for t in x[::-1]]))

Submission status: Accepted

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_s(): return list(input().split())

N,K = inpl()
xx = inpl()
ans = INF
for i in range(N-K+1):
	left,right = xx[i], xx[i+K-1]

	if left*right < 0:
		MIN = min(abs(left),abs(right))
		MAX = max(abs(left),abs(right))
		tmp = MIN*2+MAX
	else:
		tmp = max(abs(left),abs(right))

	ans = min(tmp,ans)

print(ans)

Submission status: Accepted

Solution code:
def ii():
    return int(input())
def mi():
    return map(int, input().split())
def li():
    return list(mi())

N, K = mi()
A = li()

i = K - 1
ans = 10 ** 18
while i < N:
    l = A[i - K + 1]
    r = A[i]
    if 0 < l:
        ans = min(ans, r)
    elif r < 0:
        ans = min(ans, -l)
    else:
        ans = min(ans, 2 * r - l, -2 * l + r)
    i += 1
print(ans)

Submission status: Accepted

Solution code:
n, k = [int(x) for x in raw_input().split()]
x = [int(x) for x in raw_input().split()]
ans = 10000000000000000000
for i in xrange(0, n - k + 1):
    l = x[i]
    r = x[i + k - 1]
    ans = min(ans, max(abs(l), abs(r)) if l * r > 0 else min(abs(l), abs(r)) + r - l)

print ans

Submission status: Accepted

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

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

print(min(dis))

Submission status: Accepted

Solution code:
from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

def read():
  return int(input())

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

N, K = reads()
x = reads()

ans = 1 << 60

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

print(ans)

Submission status: Accepted

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

ret= 1000000000
for i in range(n-k+1):
    a = x[i]
    b = x[i+k-1]
    ret =min([ret, abs(a) + abs(a - b), abs(b) + abs(a - b)])

print(ret)

Submission status: Accepted

Solution code:

import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline

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

ans=10**9

for i in range(n-k):
    # light up [i,i+k]
    if x[i]<0 and x[i+k]<0:
        ans=min(ans,-x[i])
    elif x[i]>0 and x[i+k]>0:
        ans=min(ans,x[i+k])
    else:
        t=abs(x[i])+abs(x[i+k])+min(abs(x[i]),abs(x[i+k]))
        ans=min(ans,t)
print(ans)

Submission status: Runtime Error

Solution code:
a = [list(map(int, input().split())) for i in range(2)]
k = a[0][1]

num_list = a[1]

positive_list = []
negative_list = []

ans_positive = []
ans_negative = []

ans_list = []

for _ in num_list:
    if _ > 0:
        positive_list.append(_)
    elif _ < 0:
        negative_list.insert(0, _)
    else:
        if num_list != [0]:
        k -= 1

for _ in list(range(len(positive_list))):
    if not 0 <= k - _ - 2 < len(negative_list):
        continue
    ans_positive.append(2 * positive_list[_] - negative_list[k - _ - 2])

for _ in list(range(len(negative_list))):
    if not 0 <= k - _ - 2 < len(positive_list):
        continue
    ans_negative.append(-2 * negative_list[_] + positive_list[k - _ - 2])

if ans_positive:
    ans_list.append(min(ans_positive))

if ans_negative:
    ans_list.append(min(ans_negative))

if k <= len(positive_list):
    ans_list.append(positive_list[k - 1])

if k <= len(negative_list):
    ans_list.append(-1 * negative_list[k - 1])

if ans_list == []:
    print(0)

else:
    print(min(ans_list))

Submission status: Runtime Error

Solution code:
a = [list(map(int, input().split())) for i in range(2)]
k = a[0][1]

num_list = a[1]

positive_list = []
negative_list = []

ans_positive = []
ans_negative = []

ans_list = []

for _ in num_list:
    if _ > 0:
        positive_list.append(_)
    elif _ < 0:
        negative_list.insert(0, _)
    else:
        k -= 1

for _ in list(range(len(positive_list))):
    if not 0 <= k - _ - 2 < len(negative_list):
        continue
    ans_positive.append(2 * positive_list[_] - negative_list[k - _ - 2])

for _ in list(range(len(negative_list))):
    if not 0 <= k - _ - 2 < len(positive_list):
        continue
    ans_negative.append(-2 * negative_list[_] + positive_list[k - _ - 2])

if ans_positive:
    ans_list.append(min(ans_positive))

if ans_negative:
    ans_list.append(min(ans_negative))

if k <= len(positive_list):
    ans_list.append(positive_list[k - 1])

if k <= len(negative_list):
    ans_list.append(-1 * negative_list[k - 1])

if ans_list == []:
    print(0)

else:
    print(min(ans_list))

Submission status: Runtime Error

Solution code:
a = [list(map(int, input().split())) for i in range(2)]
k = a[0][1]

num_list = a[1]

positive_list = []
negative_list = []

ans_positive = []
ans_negative = []

ans_list = []

for _ in num_list:
    if _ > 0:
        positive_list.append(_)
    elif _ < 0:
        negative_list.insert(0, _)
    else:
        k -= 1

for _ in list(range(len(positive_list))):
    if not 0 <= k - _ - 2 < len(negative_list):
        continue
    ans_positive.append(2 * positive_list[_] - negative_list[k - _ - 2])

for _ in list(range(len(negative_list))):
    if not 0 <= k - _ - 2 < len(positive_list):
        continue
    ans_negative.append(-2 * negative_list[_] + positive_list[k - _ - 2])

ans_list.append(min(ans_positive))
ans_list.append(min(ans_negative))
if k < len(positive_list):
    ans_list.append(positive_list[k])

if k < len(negative_list):
    ans_list.append(-1 * negative_list[k])

print(min(ans_list))

Submission status: Runtime Error

Solution code:
from scipy.special import comb
import itertools

n, k = map(int, input().split())
x = list(map(int, input().split()))
X = []
m = 3*10**8

for v in itertools.combinations(x, k):
    X.append(list(v))

for i in range(comb(n, k, exact=True)):
    m0 = min(X[i])
    m1 = max(X[i])
    a = min(abs(abs(m0)+abs(m1-m0), abs(m1)+abs(m1-m0)))
    if m > a:
        m = a
print(m)

Submission status: Runtime Error

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

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
N,K =(int(i) for i in input().split())
x = (int(i) for i in input().split())
i = 0
t_min = float("inf")
while i+K <= N :
  left = abs(x[i])+abs(x[i+K-1]-x[i])
  right = abs(x[i+K-1])+abs(x[i+K-1]-x[i])
  if min(left,right)<t_min:
    t_min = min(left,right)
  i += 1
print(t_min)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
import bisect

def main():
  n, k, *lst = map(int, open(0).read().split())
  z = bisect.bisect_left(lst, 0)
  idx = max(z - k + 1, 0)
  print(min(min(abs(i), j) + j - i for i, j in zip(lst[idx:], lst[idx + k - 1:])))

if __name__ == '__main__':
  main()

Submission status: Runtime Error

Solution code:
import bisect

n, k, *lst = map(int, open(0).read().split())
z = bisect.bisect_left(lst, 0)
if not z:
  print(lst[z + k - 1])
  quit()
assert lst[z] > 0
res = float('inf')
for i in range(max(z - k + 1, 0), min(z, n - k) + 1):
  tmp = lst[i + k - 1] - lst[i] + min(abs(lst[i]), lst[i + k - 1])
  if tmp < res:
    res = tmp
print(res)

Submission status: Runtime Error

Solution code:
    from bisect import bisect
    n,k=map(int,input().split())
    x=list(map(int,input().split()))
    g=bisect(x,0)
    if x[n-1]<=0 or x[0]>=0:
        print(max(abs(x[k-1]),abs(x[0])))
    else:
        if g>=k:
            s=g-k
        else:
            s=0
        t=0
        while s<=n-k:
            if x[s]<0 and x[s+k-1]>0:
                if t==0:
                    t=min(2*abs(x[s])+x[s+k-1],abs(x[s])+2*x[s+k-1])
                else:
                    t=min(t,2*abs(x[s])+x[s+k-1],abs(x[s])+2*x[s+k-1])
            else:
                t=min(t,max(abs(x[s]),abs(x[s+k-1])))
            s+=1
        print(t)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
LOCAL = len(sys.argv) > 1 and sys.argv[1] == 'LOCAL'


def dprint(*args):
  if LOCAL:
    print(*args)


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

k -= x.count(0)

if k <= 0:
  print(0)
  exit()

n = [0]
for e in reversed(x):
  if e < 0:
    n.append(-e)

p = [0]
for e in x:
  if e > 0:
    p.append(e)


dprint(n, p)

anses = []

for i in range(k + 1):
  j = k - i
  if i == 0:
    pass
  elif 0 <= i < len(p) and 0 <= j < len(n):
    anses.append(p[i] * 2 + n[j])
    anses.append(p[i] + n[j] * 2)

dprint(anses)

print(min(anses))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
LOCAL = len(sys.argv) > 1 and sys.argv[1] == 'LOCAL'


def dprint(*args):
  if LOCAL:
    print(*args)


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

k -= x.count(0)

if k == 0:
  print(0)
  exit()

n = [0]
for e in reversed(x):
  if e < 0:
    n.append(-e)

p = [0]
for e in x:
  if e > 0:
    p.append(e)


dprint(n, p)

anses = []

for i in range(k + 1):
  j = k - i
  if i == 0:
    pass
  elif 0 <= i < len(p) and 0 <= j < len(n):
    anses.append(p[i] * 2 + n[j])
    anses.append(p[i] + n[j] * 2)

dprint(anses)

print(min(anses))

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
x = list(int(input()) for _ in range(n))
x2 = [abs(x[j]-x[j+1]) for j in range(n-1)]
ans = []

try:
    for i in range(n-k+1):
        s = sum(x2[i:i+k-1]) + abs(x[i])
        ans.append(s)
except IndexError:
    pass

print(min(ans))