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

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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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()

Solution (Python):
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)

Solution (Python):
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)): 
  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)

Solution (Python):
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)

Solution (Python):


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


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)

Solution (Python):
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)
    
    ans = float('inf')
    for p in range(k + 1):
        li = i0 - k + p
        ri = i0 + p
        
        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))

Solution (Python):
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)

Solution (Python):
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

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):


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

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):


import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq





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 
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)

Solution (Python):

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







def abs(n):
    if n >= 0:
        return n
    else:
        return -n
times = []                      
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))

Solution (Python):
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)):
        
        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)))

Solution (Python):
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)

Solution (Python):
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))

Solution (Python):

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

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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]]))

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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

Solution (Python):
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))

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):

import sys

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