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 numpy as np

def solve():
    N, K = map(int, input().split())
    C = np.array(list(map(int,input().split())))
    z = (C<0).sum()
    D = set()
    for i in range(N-K+1):
        l = -min(C[i],0)
        r = max(C[i+K-1],0)
        d = 2*l+r if l < r else 2*r+l
        D.add(d)
    return str(min(D))

if __name__ == '__main__':
    print(solve())

Submission status: Accepted

Solution code:
n,k = map(int,raw_input().split())

arr = map(int,raw_input().split())

ans = float("inf")
import bisect
t = bisect.bisect_right(arr,0)
arr.insert(t,0)
for i in range(n+1):
	if i-k > -1:
		ans = min(ans, abs(arr[i-k]) + abs(arr[i]) + min(abs(arr[i-k]), abs(arr[i])))

print ans

Submission status: Accepted

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

x = list(map(int,input().split()))
ans = 100000000000000

a = 0
while a != n:
	if x[a] >= 0:
		break
	a += 1
for i in range(max(0,a-k),n-k+1):
	if x[i+k-1] <= 0:
		ans = min(ans,-x[i])
	elif x[i] >= 0:
		ans = min(x[i+k-1],ans)
	else:
		ans = min(x[i+k-1]-x[i]+min(-x[i],x[i+k-1]),ans)
print(ans)

Submission status: Accepted

Solution code:
import numpy as np

def main():
    n, k = map(int,input().split())
    lst = list(map(int,input().split()))
    arr = np.array(lst)

    if np.any(arr == 0):
        if k == 1:
            print(0)
            exit()
        k -= 1

    plus = arr[np.where(arr>0)]
    len_plus = len(plus)
    plus = np.insert(plus,0,0)
    minus = arr[np.where(arr<0)][::-1]
    len_minus = len(minus)
    minus = np.insert(minus,0,0)

   # print(plus)
    #print(len_plus)
    #print(plus[len_plus])
    #print(minus)
    #print("#######")

    anslist = []
    ans = 100000000000000000000


    for i in range(k):
        if len_plus < k:
            try:
                ans = plus[len_plus-i] + (abs(minus[i+(k-len_plus)])*2)
                anslist.append(ans)
            except:
                break

        elif len_plus >= k:
            try:
                ans = plus[k-i] + (abs(minus[i])*2)
                #print(ans)
                anslist.append(ans)
            except:
                break

    for i in range(k):
        if len_minus < k:
            try:
                ans = abs(minus[len_minus-i]) + (plus[i+(k-len_minus)]*2)
                anslist.append(ans)
            except:
                break
        else:
            try:
                ans = abs(minus[k-i]) + (plus[i]*2)
                anslist.append(ans)
            except:
                break


    #print(anslist)
    print(min(anslist))



if __name__ == "__main__":
        main()

Submission status: Accepted

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

x = -1
for i in range(len(li)):
	if li[i] >= 0:
		x = i
		break

if x == -1:
	print(li[-K] * -1)

elif not x :
	print(li[K-1])

else:
	score = float("inf")
	for i in range(K):
		if i == K-1:
			try:
				score = min(li[x+i], score)
			except:
				pass
			try:
				if x-i-1 >= 0:
					score = min(li[x-i-1] * -1, score)
			except:
				pass
		else:
			try:
				if x-(K-1-i) >= 0:
					score = min(li[x+i] * 2 + li[x-(K-1-i)] * -1, score)
			except:
				pass
			try:
				if x-i-1 >= 0:
					score = min(li[x-i-1] * -2 + li[x+K-2-i], score)
			except:
				pass
	print(score)

Submission status: Accepted

Solution code:
import sys

N, K = map(int, sys.stdin.readline().strip().split(" "))
X = map(int, sys.stdin.readline().strip().split(" "))

isZero = False
zeroInd = 0
for x in X:
    if x == 0:
        isZero=True
    if x < 0:
        zeroInd+=1
    else:
        break

zeroInd-=1

if isZero:
    X.remove(0)
    K -= 1

if K == 0:
    print(0)
    sys.exit(0)

ans = []

for k in range(K+1):
    a = -1
    if zeroInd + k < len(X):
        a = X[zeroInd+k]

    b = -1
    if len(X) > zeroInd+k-K+1 >= 0:
        b = X[zeroInd+k-K+1] * -1

    if b != -1 and k == 0:
        ans.append(b)
    elif a != -1 and k == K:
        ans.append(a)
    elif a != -1 and b != -1:
        ans.append(a*2+b)
        ans.append(b*2+a)

print(min(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):
    a,b=X[i],X[i+k-1]
    if b<0:
        ans=min(ans,-a)
    elif a>0:
        ans=min(ans,b)
    else:
        tmp=min(-a,b)*2+max(-a,b)
        ans=min(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
#-*-coding:utf-8-*-

def main():
    n, k = map(int, input().split())
    x_list = list(map(int, input().split()))
    ans = float('inf')

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

if __name__ == '__main__':
    main()

Submission status: Accepted

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

arr = list(map(int, input().split()))
zero_ind = len(arr)
for i, e in enumerate(arr):
    if e > 0:
        zero_ind = i
        break
    elif e == 0:
        zero_ind = i + 1
        arr = arr[:i] + arr[i+1:]
        K -= 1
        break
if K == 0:
    print(0)
else:
    # 右へ
    min_val = (10**8) * K
    for i in range(1,K+1):
        # i個0以上からK-i個0未満から
        if zero_ind + i - 1 >= len(arr) or zero_ind - (K - i) < 0:
            continue
        if i == K:
            val = arr[zero_ind + i - 1]
        else:
            val = 2 * arr[zero_ind + i - 1] - arr[zero_ind - (K - i)]
        if min_val > val:
            min_val = val

    # 左へ
    for i in range(1,K+1):
        # i個0以上からK-i個0未満から
        if zero_ind + K - i - 1 >= len(arr) or zero_ind - i < 0:
            continue
        if i == K:
            val = -1 * arr[zero_ind - i]
        else:
            val = arr[zero_ind + K - i - 1] - 2 * arr[zero_ind - i]
        if min_val > val:
            min_val = val

    print(min_val)

Submission status: Accepted

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

lst = []
for i in range(N-K+1):
    if x[i] <= 0 and x[i+K-1] <= 0:
        lst.append(abs(x[i]))
    elif x[i] >= 0 and x[i+K-1] >= 0:
        lst.append(x[i+K-1])
    else:
        d1 = abs(x[i]) + x[i+K-1] - x[i]
        d2 = x[i+K-1] + x[i+K-1] - x[i]
        lst.append(min(d1, d2))
print(min(lst))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import numpy
na = lambda: list(map(int, input().split()))

n, k = na()
x = na()
l = []
m, p = 0, 0
for i in range(n-1):
    hoge = x[i]
    if hoge < 0:
        m += 1
    l.append(abs(x[i+1] - hoge))
p = n-m
l = numpy.cumsum([0]+l)

ans = 10 ** 10

for i in range(max(0, m-k), min(n-p+1, n-k+1)):
    ans = min(ans, min(abs(x[i]), abs(x[i+k-1]))+abs(l[k-1+i]) - abs(l[i]))

print(ans)

Submission status: Accepted

Solution code:
import sys

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()


if __name__ == "__main__":
    n, k = LI()
    X = LI()
    l_count = sum((x <= 0 for x in X))
    r_count = n - l_count

    if l_count == 0:
        print(X[k-1])
    elif r_count == 0:
        print(abs(X[-k]))
    else:
        times = []
        for i in range(l_count):
            try:
                left = X[l_count - i - 1]
                right = X[l_count + k - i - 2]
                times.append(abs(2 * left) + abs(right))
                times.append(abs(left) + abs(2 * right))
            except:
                continue
        print(min(times))

Submission status: Accepted

Solution code:
# cook your dish here
import bisect 
n,k = map(int,input().split())
x = list(map(int,input().split()))

w  = x.count(0)
for i in range(w):
    x.remove(0)

if k <= w:
    print(0)
else:
    k = k -w
    #print(x)

    r = bisect.bisect_left(x,0)
    
    if x[-1]<0:
        print(abs(x[len(x)-k]))
    elif x[0] > 0:
        print(x[k-1])    
    else:
        ass = 10 ** 10
        ans = 10**10
        for i in range(r,min(len(x),r + k )):
            if i-r+1 >= k:
                ans = abs(x[i])
            
            else:
                if i - k + 1 >= 0:
                    ans = x[i] + abs(x[i-k+1]) + min(x[i],abs(x[i-k+1]))
            ass = min(ass,ans)
        if r-k >= 0:
            ans = abs(x[r-k])
        ass = min(ass,ans)
        print(ass)

Submission status: Accepted

Solution code:
from bisect import bisect_left
n, k = map(int, input().split())
a = list(map(int, input().split()))
t = bisect_left(a, 0, 0, len(a))
ans = float("inf")
if t + k <= n:
    ans = a[t + k - 1]
if t >= k:
    ans = min(ans, -a[t - k])
for i in range(max(0, t - k + 1), min(t, n-k+1)):
    ans = min(ans, a[i+k-1]-2*a[i], 2*a[i+k-1]-a[i])
print(ans)

Submission status: Accepted

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

X_pos = [x for x in X if x >= 0]
X_neg = [x for x in X if x <  0]

X_neg.reverse()

l_pos = len(X_pos)
l_neg = len(X_neg)

R = []

if l_neg == 0:
    R.append(X_pos[K-1])
elif l_pos == 0:
    R.append(-1 * X_neg[K-1])
else:
    for k in range(K):
        if k < l_pos and K-k-2 < l_neg:
            R.append(2 * X_pos[k] - X_neg[K-k-2])
        elif k >= l_pos:
            break
    for k in range(K):
        if k < l_neg and K-k-2 < l_pos:
            R.append(-2 * X_neg[k] + X_pos[K-k-2])
        elif k >= l_neg:
            break

print(min(R))

Submission status: Accepted

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

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

if (0 in X):
  K = K-1
  N = N-1
  X.remove(0)

trial = []

if X != []:
  for i in range(N-K+1):
    if (X[i] < 0) and (X[K+i-1] < 0):
      trial.append(abs(X[i]))
    if (X[i] > 0 ) and (X[K+i-1] > 0):
      trial.append(abs(X[K+i-1]))
    go = abs(X[i])*2+abs(X[K+i-1])
    back = abs(X[i])+abs(X[K+i-1])*2
    trial.append(min(go,back))
  
if trial != []:
  print(min(trial))
else:
  print(0)

Submission status: Accepted

Solution code:
import bisect
n,k=map(int,input().split())
x=list(map(int,input().split()))
idx = bisect.bisect_left(x,0)
now = max(0,idx-k)
mini =1e10
for i in range(now,n-k+1):
    if(x[i]*x[i+k-1]>=0):
        mini=min(max(abs(x[i]),abs(x[i+k-1])),mini)
        continue
    mini = min(mini,abs(x[i])+x[i+k-1]+min(abs(x[i]),x[i+k-1]))
print(mini)

Submission status: Accepted

Solution code:
N, K = map(int, input().strip().split(" "))
x = [int(i) for i in input().split(" ")]

cur = 0
dist = 1000000000
if K == 1:
    dist = min(x)
elif K == N:
    if (x[0] <= 0) and (x[N-1] > 0):
        dist = min(abs(x[0]) * 2 + x[N-1], abs(x[0]) + x[N-1] * 2)
    elif x[N-1] <= 0:
        dist = abs(x[0])
    else: #x[i] > 0
        dist = x[N-1]
else:
    for i in range(N-K+1):
        cur_dist = 0
        if (x[i] <= 0) and (x[i+K-1] > 0):
            cur_dist = min(abs(x[i]) * 2 + x[i+K-1], abs(x[i]) + x[i+K-1] * 2)
        elif x[i+K-1] <= 0:
            cur_dist = abs(x[i])
        else: #x[i] > 0
            cur_dist = x[i+K-1]
        if dist >= cur_dist:
            dist = cur_dist
        if x[i] > 0:
            break

print(dist)

Submission status: Accepted

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

k = []
# print(X)

k0 = abs(X[0])
for n in range(0+1, K):
    k0 += X[n] - X[n-1]
k.append(k0)
for i in range(1, len(X)-K+1):
    ki = k[i-1] - (X[i] - X[i-1]) + (X[i+K-1] - X[i+K-2]) - abs(X[i-1]) + abs(X[i])
    k.append(ki)
# print(min(k))

l = []
l0 = abs(X[N-1])
for n in range(N-1, N-K, -1):
    l0 += X[n] - X[n-1]
# print(l0)
l.append(l0)
for i in range(1, len(X)-K+1):
    # print(i, i-1, i+K, i+K-1)
    li = l[i-1] - (X[N-i] - X[N-i-1]) + (X[N-K-i+1] - X[N-K-i]) - abs(X[N-i]) + abs(X[N-i-1])
    # print(li)
    l.append(li)
print(min(min(k), min(l)))

Submission status: Accepted

Solution code:
import bisect
n, k = map(int, input().split())
x = list(map(int, input().split()))
z = bisect.bisect_left(x, 0)
a = sorted(map(abs, x[:z]))
b = x[z:]
ans = float("inf")
if a and b:
    for i in range(min(k, len(a))):
        if k - i - 2 >= len(b):
            continue
        ans = min(ans, min(a[i], b[k - i - 2]) * 2 + max(a[i], b[k - i - 2]))
    print(ans)
elif a:
    print(a[k - 1])
else:
    print(b[k - 1])

Submission status: Accepted

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

Y = []
Z = []

for x in X:
    if x == 0:
        Y.append(0)
        Z.append(0)
    elif x < 0:
        Y.append(abs(x))
    else:
        Z.append(x)

ans = sum(Y) + sum(Z)
Y.reverse()

for i, y in zip(range(1, len(Y)+1), Y):
    if i <= k and k - i <= len(Z):
        ans = min(ans, y + (0 if k - (i + 1) < 0 else 2 * Z[k-(i+1)]))

for i, z in zip(range(1, len(Z)+1), Z):
    if i <= k and k - i <= len(Y):
        ans = min(ans, (0 if k - (i + 1) < 0 else 2 * Y[k-(i+1)]) + z)

print(ans)

Submission status: Accepted

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

d = []
for n in range(N-K+1):
  l = abs(cans[n]) + abs(cans[n  + (K-1)] - cans[n])
  r = abs(cans[n  + (K-1)]) + abs(cans[n  + (K-1)] - cans[n])
  d.append(min(l,r))

print(min(d))

Submission status: Accepted

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

minp = 0
if X[N-1] <0:
    minp = N-1
else:
    while X[minp] < 0:
        minp += 1

lidx = 0
if minp > K:
    lidx = minp - K
ridx = lidx + K - 1
left = X[lidx]
right = X[ridx]
mind = right - left + min(abs(left), abs(right))

while ridx < N and left <= minp:
    left = X[lidx]
    right = X[ridx]
    mind = min(mind, right - left + min(abs(left), abs(right)))
    lidx += 1
    ridx += 1

print(mind)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
cs   = list(map(int, input().split()))
t    = -1
i    = 0

while i + k <= len(cs) and cs[i] < 0:
    if cs[i + k - 1] < 0:
        x = abs(cs[i])
    else:
    	x = cs[i + k - 1] - cs[i] + min(abs(cs[i + k - 1]), abs(cs[i]))

    if t == -1 or x < t:
        t = x

    i += 1

if t == -1 or i + k <= len(cs) and cs[i + k - 1] < t:
    t = cs[i + k - 1]

print(t)

Submission status: Accepted

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

temp = [None for i in range(k)]

m = float("inf")

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

print(m)

Submission status: Accepted

Solution code:
# coding:utf-8

INF = float('inf')


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


N, K = inpl()
X = inpl()

A = [0]
B = []
for i in range(N):
    if X[i] >= 0:
        A.append(X[i])
    else:
        B.append(-X[i])
B.append(0)
B = B[::-1]

# for i in range(1, len(A)):
#     A[i] += A[i-1]
#
# for i in range(1,len(B)):
#     B[i] += B[i-1]


ans = INF
for i in range(K+1):
    cost = INF
    j = K - i
    if i > len(A) - 1 or j > len(B) - 1:
        continue

    if i == K:
        cost = A[i]

    elif j == K:
        cost = B[j]

    else:
        cost_rl = 2 * A[i] + B[j]
        cost_lr = A[i] + 2 * B[j]
        cost = min(cost_rl, cost_lr)

    ans = min(ans, cost)

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
x = list(map(int, input().split()))
minsa = 10 ** 16
#fu = 0
#sei = 0
for i in range(N-K+1):
    if x[i] <= 0 and x[i+K-1] <= 0:
        sa = -x[i]
        if minsa > sa:
            minsa = sa
            #fu = -x[i]
            #sei = 0
    if x[i] < 0 and x[i+K-1] > 0:
        sa = min(x[i + K-1], -x[i])*2 + max(x[i + K -1], -x[i])
        if minsa > sa:
            minsa = sa
            #fu = -x[i]
            #sei = x[i+K-1]
    if x[i] >= 0 and x[i+K-1] >= 0:
        sa = x[i+K-1]
        if minsa > sa:
            minsa = sa
            #fu = 0
            #sei = x[i+K-1]
print(minsa)
#print(fu)
#print(sei)
#print(min(fu,sei) * 2 + max(fu,sei))

Submission status: Accepted

Solution code:
import copy

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

t_list = []

if 0 in x_list:
    zero_ind = x_list.index(0)

    for start_ind in range(max(0, zero_ind - k), min(zero_ind + 1, n - k + 1)):
        # print(start_ind)
        minv = x_list[start_ind]
        maxv = x_list[start_ind + k - 1]
        # print(minv, maxv)

        if minv < 0 < maxv:
            t = min(2 * abs(minv) + maxv, abs(minv) + 2 * maxv)

        else:
            t = max(abs(minv), abs(maxv))

        t_list.append(t)
        # print("t={}".format(t))

else:
    x_list2 = copy.copy(x_list)
    x_list2 = x_list2 + [0]
    x_list2 = sorted(x_list2)
    zero_ind = x_list2.index(0)

    for start_ind in range(max(0, zero_ind - k), min(zero_ind + 1, n - k + 1)):
        # print(start_ind)
        minv = x_list[start_ind]
        maxv = x_list[start_ind + k - 1]
        # print(minv, maxv)

        if minv < 0 < maxv:
            t = min(2*abs(minv) + maxv, abs(minv) + 2 * maxv)

        else:
            t = max(abs(minv), abs(maxv))

        t_list.append(t)


print(min(t_list))

Submission status: Accepted

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

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

ans = float("inf")
for i in range(N):
    j = i + K-1
    if j >= N:
        break
    if x[i]*x[j] > 0:
        continue
    ans = min(ans, -2*x[i]+x[j], -x[i]+2*x[j])
    
print(ans)

Submission status: Accepted

Solution code:
import math
N,K = map(int,input().split())
xs = input().split()
res_list = []
for i in range(N-K+1):
    if int(xs[i]) >0:
        diff = int(xs[i+K-1])
        res_list.append(diff)
        break
    elif int(xs[i]) <= 0 and int(xs[i+K-1]) > 0:
        diff = 2 * min(abs(int(xs[i])),abs(int(xs[i+K-1]))) + max(abs(int(xs[i])),abs(int(xs[i+K-1])))
    elif int(xs[i+K-1]) <= 0:
        diff = abs(int(xs[i]))
    res_list.append(diff)
print(min(res_list))

Submission status: Accepted

Solution code:
inputs = input().strip().split()

N = int(inputs[0])
K = int(inputs[1])

inputs = input().strip().split()
problem = list(map(lambda x: int(x), inputs))

ans = 10000000000000000000000000

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

print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

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

ans = float('inf')
for i in range(N-K+1):
    tmp = float('inf')
    # 範囲が0を含む
    if xN[i] <= 0 <= xN[i+K-1]:
        # 距離の短い方を往復する
        if abs(xN[i]) <= abs(xN[i+K-1]):
            tmp = abs(xN[i])*2 + abs(xN[i+K-1])
        else:
            tmp = abs(xN[i]) + abs(xN[i+K-1])*2
    # 範囲が全て0より大きい
    elif xN[i] > 0:
        tmp = abs(xN[i+K-1])
    # 範囲が全て0より小さい
    elif xN[i+K-1] < 0:
        tmp = abs(xN[i])
    ans = min(tmp, ans)

print(ans)

Submission status: Accepted

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

# left point = i
ans = 1e9
for i in range(N-K+1):
    if X[i] >= 0:
      dist = X[i+K-1]
    elif X[i+K-1] <= 0:
      dist = abs(X[i])
    else:
      dist = min(X[i+K-1] * 2 - X[i], X[i+K-1] - 2 *X[i]) 
    #print(dist)
    ans = min(ans, dist)

print(ans)

Submission status: Accepted

Solution code:
import numpy as np
N, K =map(int, input().split())
X = [int(_) for _ in input().split()]
X2 = np.zeros((N,))
X2 += X
minus = X2[X2 < 0] * (-1)
minus.sort()
plus = X2[X2 >= 0]
lenM, lenP = len(minus), len(plus)

def length(i, j):
    if i == 0:
        return plus[j-1]
    if j == 0:
        return  minus[i-1]
    else:
        LtoR = min(minus[i-1], plus[j-1])
        return plus[j-1] + minus[i-1] + LtoR

minLength = 1000000000
for i in range(0, K+1):
    a, b = i, K-i
    if lenM >= a and lenP >= b :
        minLength = min(minLength, length(a, b))

print(int(minLength))

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right

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

zero_left = bisect_left(x, 0)
zero_right = bisect_right(x, 0)
m = x[:zero_left]
p = x[zero_right:]
zero_count = zero_right - zero_left
k -= zero_count
if k <= 0:
	print(0)
	exit()

y = m[-k:] + p[:k]
min_time = 1000000000000000000000000
for i in range(len(y)-k+1):
	l, r = y[i], y[i+k-1]
	time = r-l + min(abs(l), abs(r))
	if time < min_time:
		min_time = time

print(min_time)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8
#

import copy

            
    
def main(n, k, l):
    cost_l = []

    if k == 0:
        print(0)
        return
    
    if k == 1:
        t = [abs(l[i]) for i in range(len(l)) ]
        print(min(t))
        return
    
    for i in range(n - k + 1):
        mae = i
        ato = i + k - 1
        if l[mae] * l[ato] < 0:
            cost_l.append(min(- l[mae] * 2 + l[ato], - l[mae] + l[ato] * 2))
        elif l[mae] >= 0:
            cost_l.append(l[ato])
        elif l[ato] <= 0:
            cost_l.append(-l[mae])
            
    print(min(cost_l))

    
    
if __name__ == '__main__':
    try:
        n, k = list(map(int,input().strip().split(" ")))
        l = list(map(int,input().strip().split(" ")))
        main(n, k, l)
    except EOFError:
        pass

Submission status: Accepted

Solution code:

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

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

x_plus = sorted([x for x in x_list if x > 0 ])
x_minus = sorted([x for x in x_list if x < 0 ], reverse=True)
zero_x = [x for x in x_list if x == 0 ]

if len(x_plus) == 0 and len(x_minus) == 0:
    print(0)
elif len(x_plus) == 0:
    print(abs(x_minus[k-1-len(zero_x)]))
elif len(x_minus) == 0:
    print(abs(x_plus[k-1-len(zero_x)]))
else:
    max_x = max(x_plus)
    min_x = min(x_minus)

    cost_list = []
    for i in range(len(x_plus)):
        cost = 0
        cnt = i+1 + len(zero_x)
        if len(x_minus)+cnt < k or cnt > k:
            continue
        if cnt == k:
            cost += abs(x_plus[i])
        else:
            cost+=abs(x_minus[k-cnt-1])*2
            cost+=abs(x_plus[i])
        cost_list.append(cost)

    for i in range(len(x_minus)):
        cost = 0
        cnt = i+1 + len(zero_x)
        if len(x_plus)+cnt < k or cnt > k:
            continue
        if cnt == k:
            cost += abs(x_minus[i])
        else:
            cost+=abs(x_plus[k-cnt-1])*2
            cost+=abs(x_minus[i])
        cost_list.append(cost)


    print(min(cost_list))

Submission status: Accepted

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

min_result = max(abs(x[0])*2, abs(x[-1])*2, abs(x[-1] - x[0])*2)

for i in range(0, len(x)-k+1):
    if x[i+k-1] <= 0:
        min_result = min(min_result, -x[i])
    elif x[i] < 0 and x[i+k-1] > 0:
        min_result = min(min_result, -x[i]*2+x[i+k-1], -x[i]+x[i+k-1]*2)
    else:
        min_result = min(min_result, x[i+k-1])

print(min_result)

Submission status: Accepted

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

if a[N-1]<0:
    a=list(reversed(list(map(abs,a))))
if N == K:
    print(a[N-1]-a[0]+min(abs(a[0]),abs(a[N-1])))
else:
    ans=10000000000
    for i in range(N-K):
        ans = min(ans,a[K+i-1]-a[i]+min(abs(a[i]),abs(a[K+i-1])))
    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(0,n-k+1):
    if a[i] <= 0 and a[i+k-1] <= 0:
        ans = min(ans,abs(a[i]))
    elif a[i] <= 0 and 0 <= a[i+k-1]:
        ans = min(ans,2*abs(a[i])+a[i+k-1],abs(a[i])+2*a[i+k-1])
    elif 0 <= a[i]:
        ans = min(ans,a[i+k-1])
if ans == float("inf"):
    print(0)
else:
    print(ans)

Submission status: Accepted

Solution code:
import bisect
N, K = map(int,input().split())
x = list(map(int,input().split()))
ans = 10**9
zero = bisect.bisect_left(x, 0)

if zero == 0:
    print(x[K-1])
    exit(0)

if zero+K <= N:
    ans = min(ans, x[zero+K-1])
if zero >= K:
    ans = min(ans, -x[zero-K])

if zero != N:
    for k in range(K-1):
        if 0 <= K+zero-k-2 < N and 0 <= zero-k-1 < N: 
            ans = min(ans,2*x[K+zero-k-2]-x[zero-k-1],x[K+zero-k-2]-2*x[zero-k-1])

print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 18 00:01:41 2018

@author: Yuya
"""

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

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

n = len(z)
c = 0

for i in range(len(z)):
    if z[i]<0:
        c+=1

d = len(z)-c

mi = 100000000000000000

if c<k:
    x = 0
    y = k-1
    mi = 100000000000000000
    ope = n-k
else:
    x = c-k
    y = c-1
    
    
for i in range(n):
    if y < n:
        if z[x]<0 and z[y]<0:
            k1 = abs(z[x])
            k2 = 0
        elif z[x]>0 and z[y]>0:
            k2 = abs(z[y])
            k1 = 0
        else:
            k1 = abs(z[x])
            k2 = abs(z[y])
            
        if k1<k2:
            tmp=k1*2+k2
        else:
            tmp=k2*2+k1

        if tmp<mi:
            mi = tmp
        x+=1
        y+=1
    else:
        break

print(mi)

Submission status: Accepted

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

ans = 10**10
for i in range(0, n-k+1):
    mid = (x[i] + x[i+k-1]) // 2
    if x[i + k-1] <= 0:
        ans = min(ans, abs(x[i]))
    elif x[i] >= 0:
        ans = min(ans, abs(x[i+k-1]))
    elif mid < 0:
        ans = min(ans, abs(x[i]) + abs(x[i+k-1]) * 2)
    else:
        ans = min(ans, abs(x[i]) * 2 + abs(x[i+k-1]))

print(ans)

Submission status: Accepted

Solution code:
n,k = map(int, raw_input().split())
lis = map(int, raw_input().split())
if 0 in lis:
    k-=1
flag=0
#print lis
if k==0:
    print 0
    flag=1
if n==1 and flag==0:
    print abs(lis[0])
    flag=1
if flag==0:
    if lis[0]>0: # all positives
        print lis[k-1]
    elif lis[n-1]<0: #all negatives
        print abs(lis[n-k])
    else:
        idx = -1
        for i in range(0, n-1):
            if lis[i]<0 and lis[i+1]>=0:
                idx = i
                break
        #print idx
        lol =[]
        x=0
        lol.append(abs(lis[idx]))
        for i in range(idx-1,-1,-1):
            lol.append(lol[x]+abs(lis[i]))
            x+=1
        #print lol
        lol1=[]
        x=0
        lol1.append(lis[idx+1])
        for i in range(idx+2,n,1):
            lol1.append(lol1[x]+(lis[i]))
            x+=1
        #print lol1

        lol=lol[::-1]
        lol3=[]
        for i in lol:
            lol3.append(i)
        for i in lol1:
            lol3.append(i)
        #print lol3
        
        ans=10000000000000000000000000000000000000000000
        lol=lol[::-1]


        lol =[]
        x=0
        lol.append(abs(lis[idx]))
        for i in range(idx-1,-1,-1):
            lol.append(abs(lis[i]))
            x+=1
        #print lol
        lol1=[]
        x=0
        lol1.append(lis[idx+1])
        for i in range(idx+2,n,1):
            lol1.append((lis[i]))
            x+=1
        #print lol1
        #print lol
        if k<=len(lol):
            ans=min(ans, lol[k-1])
        if k<=len(lol1):
            ans=min(ans, lol1[k-1])
        for i in range(1,len(lol)+1):
            fromright=k-i
            if fromright>len(lol1):
                continue
            val=2*lol[i-1]
            val+=(lol1[fromright-1])
            #print "val=",val
            if val<ans:
                ans=val
        
        for i in range(1,len(lol1)+1):
            fromleft=k-i
            if fromleft>len(lol):
                continue
            val=2*lol1[i-1]
            val+=(lol[fromleft-1])
            #print "val=",val
            if val<ans:
                ans=val
        print ans

Submission status: Accepted

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

xr =  [0] + [_ for _ in x if _ >= 0]
xl = [-_ for _ in x if _ < 0] + [0]
xl.reverse()

xr = xr[:k+1]
xl = xl[:k+1]

if len(xl) > len(xr):
  xr, xl = xl, xr
  
xl, xr = xl[k - (len(xr)-1):], xr[k - (len(xl)-1):]

xl.reverse()

print(min(min(2*i+j, 2*j+i) for i, j in zip(xl, xr)))