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

Xr = [0]
Xl = [0]

for x in X:
    if x>=0:
        Xr.append(x)
    else:
        Xl.append(-x)
Xl.sort()

S = []
for i in range(K+1):
    r = i
    l = K-i
    if r<=len(Xr)-1 and l<=len(Xl)-1:
        S.append(2*min(Xr[r],Xl[l]) + max(Xr[r],Xl[l]))
    
print(min(S))

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7

def LI(): return list(map(int,input().split()))
def I(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  n,k=LI()
  l=LI()

  mn=inf
  for i in range(n-k+1):
    a=l[i]
    b=l[i+k-1]

    if a<0 and b>0:
      mn=min(mn,abs(a)+abs(b)*2,abs(a)*2+abs(b))
    else:
      mn=min(mn,max(abs(a),abs(b)))

  return mn

print(main())

Submission status: Accepted

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

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

ans=10000000000

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

print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
a=list(map(int,input().split()))
def idou(a,b):
    if a<=0<=b:
        return 2*min(abs(a),abs(b))+max(abs(a),abs(b))
    else:
        return max(abs(a),abs(b))

print(min([idou(a[i],a[i+K-1]) for i in range(N-K+1)]))

Submission status: Accepted

Solution code:
# INPUT
# 普通の入力
n, k = map(int, input().split())
x = list(map(int, input().split()))

# PROCESS

# 全探索
answers = []

def start_to_end(start, end):
  first_move = abs(start)
  s_to_e_cost = abs(end - start)
  return first_move + s_to_e_cost

def end_to_start(start, end):
  first_move = abs(end)
  s_to_e_cost = abs(end - start)
  return first_move + s_to_e_cost

for s_idx in range(len(x)-k+1):
  start = x[s_idx]
  end = x[s_idx+k-1]
  # s -> e
  answers.append(start_to_end(start, end))
  # e -> s
  answers.append(end_to_start(start, end))

answer = min(answers)

# OUTPUT
print(answer)

Submission status: Accepted

Solution code:

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

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


xpl = []
xmi = []

for i in x:

    if i == 0:
        N -= 1
        K -= 1

    elif i < 0:
        xmi.append(-i)

    elif i > 0:
        xpl.append(i)

xmi.sort()


if K == 0:
    ans = 0

elif len(xmi) == 0:

    ans = xpl[K - 1]

elif len(xpl) == 0:

    ans = xmi[K - 1]

else:

   npl = K
   nmi = 0
   ans = -1

   while npl >= 0:

        if npl <= len(xpl) and nmi <= len(xmi):

           leng = max(xpl[npl-1],xmi[nmi-1]) + 2 * min(xpl[npl-1],xmi[nmi-1])

           if ans < 0  or  ans > leng:
               ans = leng

        npl -= 1
        nmi += 1

print (ans)

Submission status: Accepted

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

mini = 10**9
for i in range(n-k+1):
    flg1 = abs(ls[i])+abs(ls[i]-ls[i+k-1])
    flg2 = abs(ls[i+k-1])+abs(ls[i]-ls[i+k-1])
    mini = min(flg1,flg2,mini)
print(mini)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
ans = 1000000000
for i in range(n-k+1):
    if x[i+k-1] < 0:
        ans = min(ans, -x[i])
    elif x[i] < 0 <= x[i+k-1]:
        ans = min(ans, -2*x[i]+x[i+k-1])
        ans = min(ans, -x[i]+2*x[i+k-1])
    else: ans = min(ans, x[i+k-1])
print(ans)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7

def LI(): return list(map(int,input().split()))
def I(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  n,k=LI()
  l=LI()

  mn=inf
  for i in range(n-k+1):
    a=l[i]
    b=l[i+k-1]

    if a<0 and b>0:
      mn=min([mn,abs(a)+abs(b)*2,abs(a)*2+abs(b)])
    else:
      mn=min(mn,max(abs(a),abs(b)))

  return mn

print(main())

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 abs(x[i]) <= abs(x[i+K-1]):
        ans = min(ans,abs(x[i])+abs(x[i+K-1]-x[i]))
    else:
        ans = min(ans,abs(x[i+K-1])+abs(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()))
res = 10**10
for i in range(N-K+1):
    if X[i]*X[i+K-1] >= 0:
        res = min(res,max(abs(X[i+K-1]),abs(X[i])))
    else:
        res = min(res,abs(X[i])*2+X[i+K-1],X[i+K-1]*2+abs(X[i]))
print(res)

Submission status: Accepted

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


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

print(min(ans))

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N, K, *x = map(int, open(0).read().split())
ans = 1e9
for i in range(N - K + 1):
    l = x[i]
    r = x[i + K - 1]
    ans = min(ans, abs(l) + (r - l), abs(r) + (r - l))
    
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,k = list(map(int,input().split()))
data = [int(s) for s in input().split()]
ans =[]
for i in range(n-k + 1):
    ans.append(abs(data[i]) + abs(data[i+k-1] - data[i]))
for i in range(n-k + 1):
    ans.append(abs(data[i+k -1]) + abs(data[i+k-1] - data[i]))

print(min(ans))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7

def LI(): return list(map(int,input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  n,k=LI()
  l=LI()

  if l.count(0)>0:
    k-=1
    l.remove(0)

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

  if len(l)==0:
    print(0)
    exit()

  idx=len(l)-1
  for i in range(len(l)):
    if l[i]>0:
      idx=i
      break
  if max(l)<0:
    idx=len(l)

  l1=[abs(x) for x in l[idx:]]
  l2=[abs(x) for x in l[:idx]]
  l2.reverse()

  # print(l1)
  # print(l2)

  mn=inf
  for i in range(len(l1)):
    if i+1>=k:
      mn=min(mn,l1[i])
    else:
      if len(l2)>=k-(i+1):
        # print(l1[i],l2[k-(i+1)-1])
        mn=min(mn,l1[i]+2*l2[k-(i+1)-1])

  for i in range(len(l2)):
    if i+1>=k:
      mn=min(mn,l2[i])
    else:
      if len(l1)>=k-(i+1):
        # print(l2[i],l1[k-(i+1)-1])
        mn=min(mn,l2[i]+2*l1[k-(i+1)-1])

  print(mn)

main()
# print(main())

Submission status: Accepted

Solution code:
N, K = [int(_) for _ in input().split()]
x = [int(_) for _ in input().split()]
pos_i = -1
for i in range(len(x)):
    if x[i] > 0:
        pos_i = i
        break

min_t = 300000000
if pos_i == -1:
    min_t = -x[-K]
else:
    for i in range(N-K+1):
        if i+K-1 < pos_i:
            min_t = min(min_t, -x[pos_i-K])
        elif pos_i <= i:
            min_t = min(min_t, x[pos_i+K-1])
        else:
            min_t = min(min_t, x[K+i-1]-x[i]*2, x[K+i-1]*2-x[i])

print(min_t)

Submission status: Accepted

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

ans = 10**9
for i in range(N-K+1):
    l = X[i]
    r = X[i+K-1]
    if l < 0 and r <= 0:
        tmp = -l
    elif l >= 0 and r > 0:
        tmp = r
    else:
        tmp = min(abs(l),r)*2 + max(abs(l),r)
    ans = min(ans,tmp)
print(ans)

Submission status: Accepted

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

if X[0] >= 0:
    print(X[K - 1])
    exit()

if X[-1] <= 0:
    print(-X[N - K])
    exit()

ans = float('inf')
for i in range(K, N + 1):
    l = i - K
    r = i - 1
    if X[l] <= 0 <= X[r]:
        abs_l = -X[l]
        abs_r = X[r]
        dist = 0
        if abs_l > abs_r:
            dist = 2 * abs_r + abs_l
        else:
            dist = 2 * abs_l + abs_r
        ans = min(ans, dist)
print(ans)

Submission status: Accepted

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

for i in range(N-K+1):
    l,r = x[i],x[i+K-1]
    if l < 0 and r <= 0: temp = -l
    elif l >= 0 and r > 0:   temp = r
    else:
        if -l < r:    temp = 2*(-l) + r
        else:    temp = -l + 2*r  
    
    if ans > temp:  ans = temp

print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
X=[int(i) for i in input().split()]
road=[]
for i in range(n-k+1):
    if X[i]<=0 and X[i+k-1]>=0:
        r=min(abs(X[i]),X[i+k-1])+X[i+k-1]-X[i]
    elif X[i]<=0 and X[i+k-1]<=0:
        r=abs(X[i])
    else:
        r=X[i+k-1]
    road.append(r)

print(min(road))

Submission status: Accepted

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

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

if N == 1 or K == 1:
    print(x[0])
    exit()

ans = 10**100
for i in range(N):
    if i < N-K+1:
        tmp1 = abs(x[i]) + abs(x[i] - x[i+K-1])
        tmp2 = abs(x[i+K-1]) + abs(x[i] - x[i+K-1])
        ans = min(tmp1, tmp2, ans)

print(ans)

Submission status: Accepted

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

def bsr_sub(a, v, l, r):
	if r < l:
		return l
	m = (l + r) // 2
	#print(l, m, r)
	if v < a[m]:
		return bsr_sub(a, v, l, m - 1)
	else:
		return bsr_sub(a, v, m + 1, r)

def bsr(a, v):
	return bsr_sub(a, v, 0, len(a) - 1)

cost, center = [], bsr(X, 0)
for l in range(max(0, center - K), min(N - K + 1, center + 1)):
	#print(l, center, l + K - 1)
	cost += [min([abs(X[l]), abs(X[l + K - 1])]) + (X[l + K - 1] - X[l])]

print(min(cost))

Submission status: Accepted

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

cost = []

for i in range(n-k+1):
  cost_i = abs(x[i]-x[i+k-1])
  cost_i += min(abs(x[i]),abs(x[i+k-1]))
  cost.append(cost_i)
  
print(min(cost))

Submission status: Accepted

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

minus = [0]
plus = [0]
for x in X:
    if x < 0:
        minus.append(abs(x))
    elif x == 0:
        K -= 1
    else:
        plus.append(x)

#負の数の方を絶対値に基づき並べなおす
minus.sort()

a = len(minus) - 1
b = len(plus) - 1

ans = []
for i in range(max(0, K - b), min(a, K) + 1):
    ans.append(min(minus[i] * 2 + plus[K - i], minus[i] + plus[K - i] * 2))

if len(X) == 1:
    ans.append(X[0])

print(min(ans))

Submission status: Accepted

Solution code:
import sys, os, bisect

f = lambda:list(map(int,input().split()))
if 'local' in os.environ :
    sys.stdin = open('./input.txt', 'r')

def solve():
    n , k = f()
    a = f()

    ans = int(1e10)
    for i in range(n):
        if i+k-1<n:
            ans = min(ans,  abs(a[i]) + abs(a[i] - a[i+k-1]), abs(a[i+k-1]) + abs(a[i] - a[i+k-1]))

    print(ans)

solve()

Submission status: Accepted

Solution code:
import sys, os, bisect

f = lambda:list(map(int,input().split()))
if 'local' in os.environ :
    sys.stdin = open('./input.txt', 'r')

def solve():
    n , k = f()
    a = f()

    ans = int(1e10)
    for i in range(n):
        if i+k-1<n:
            cur_ans = 0
            if a[i]* a[i+k-1]>=0:
                cur_ans = max(abs(a[i+k-1]),abs(a[i]))
            else:
                cur_ans = min(2*abs(a[i])+abs(a[i+k-1]), abs(a[i]) + 2*abs(a[i+k-1]))
            ans = min(ans, cur_ans)
    
    print(ans)

solve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import bisect


def solve(N: int, K: int, x: "List[int]"):
    zi = bisect.bisect_left(x,0)

    s = max(0,zi-K)
    e = min(N-K,zi+K-1)

    res = float("inf")
    for i in range(s,e+1):
        x1 = x[i]
        x2 = x[i+K-1]
        if x2 < 0:
            res = min(res,abs(x1))
        elif x1 > 0:
            res = min(res,x2)
        else:
            res = min(res,abs(x1*2)+abs(x2))
            res = min(res,abs(x1)+abs(x2*2))
    print(res)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    x = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(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 = 100000000000
#最初と最後だけ調べればOK
for i in range(N - K + 1):
    tmp_min = x[i]
    tmp_max = x[i + K - 1]
    ans = min(ans, min(abs(tmp_min), abs(tmp_max)) + abs(tmp_min - tmp_max))
print(ans)

Submission status: Accepted

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

ans = 100000000000
#最初と最後だけ調べればOK
for i in range(N - K + 1):
    tmp_min = x[i]
    tmp_max = x[i + K - 1]
    tmp = abs(tmp_min) + abs(tmp_min - tmp_max)
    tmp2 = abs(tmp_max) + abs(tmp_min - tmp_max)
    ans = min(ans, min(tmp, tmp2))
print(ans)

Submission status: Accepted

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

ans = 100000000000
#最初と最後だけ調べればOK
for i in range(N - K + 1):
    tmp_min = x[i]
    tmp_max = x[i + K - 1]
    tmp = 0
    if tmp_min < 0:
        #混合の場合
        if tmp_max > 0:
            #+に先に行く場合
            if abs(tmp_min) > tmp_max:
                tmp = tmp_max * 2
                tmp += abs(tmp_min)
            #-に先に行く場合
            else:
                tmp = abs(tmp_min) * 2
                tmp += tmp_max
        #すべてマイナスの場合
        else:
            tmp = abs(tmp_min)
    else:
        tmp = tmp_max
    ans = min(ans, tmp)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
x = [int(_) for _ in input().split()]
ans = []
for i in range(N-K+1):
    l = abs(x[i]) + abs(x[i+K-1]-x[i])
    r = abs(x[i+K-1]) + abs(x[i+K-1]-x[i])
    ans.append(min(l,r))
print(min(ans))

Submission status: Accepted

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

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

print(ans)

Submission status: Accepted

Solution code:
def answer(n, k, x):
    ans = 2 * (x[n - 1] - x[0])


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

        temp += abs(x[i + k - 1] - x[i])

        if temp < ans:
            ans = temp

    return ans


[n, k] = list(map(int, input().split()))
x = list(map(int, input().split()))    
print(str(answer(n, k, x)))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
C - Candles
https://atcoder.jp/contests/abc107/tasks/arc101_a

"""
import sys


def solve(N, K, candles):
    ans = []
    for i in range(N-K+1):
        left = candles[i]
        right = candles[i+K-1]
        if left * right < 0:
            if abs(left) > abs(right):
                ans.append(abs(left) + abs(right)*2)
            else:
                ans.append(abs(left)*2 + abs(right))
        else:
            ans.append(max(abs(left), abs(right)))
    return min(ans)


def main(args):
    N, K = map(int, input().split())
    candles = [int(x) for x in input().split()]
    ans = solve(N, K, candles)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
INF = 1000000000
distances = [INF]*(2*(N-K+1))
for l in range(N-K+1):
    distances[l] = abs(X[l]) + abs(X[l] - X[l+K-1])
    distances[l+N-K+1] = abs(X[l+K-1]) + abs(X[l] - X[l+K-1])

print(min(distances))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
X=[int(i) for i in input().split()]
ans=1000000000000000
for n,x in enumerate(X):
    if n+K>N:break
    y=X[n+K-1]
    if x*y>=0:#同符号orどっちか０
        move=max(abs(x),abs(y))
    else:#異符号
        move=max(abs(x),abs(y))+min(abs(x),abs(y))*2
    ans=min(move,ans)
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
t = []
for i in range(N - K + 1):
  start = X[i]
  end = X[i + K - 1]
  if start * end >= 0:
    t.append(max(abs(start), abs(end)))
  else:
    t.append(end - start + min(abs(end), abs(start)))
print(min(t))

Submission status: Accepted

Solution code:
import numpy as np

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

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


def calc(m, n, default=100000000):
    tmp = 0
    if m > n:
        tmp = m + 2*n
    else:
        tmp = 2*m + n

    min = tmp if default > tmp else default

    return min


def my_index(l, i, default=False):
    if i in l:
        return True
    else:
        return default


def main():
    global x, K
    if 0 in x:
        K -= 1
        if K == 0:
            return 0

    x = np.array(x)
    positives = x[np.where(x > 0)]
    negatives = x[np.where(x < 0)]

    nega_size = np.size(negatives)
    posi_size = np.size(positives)
    if nega_size == 0:
        return positives[K-1]

    if posi_size == 0:
        return abs(negatives[-K])

    if K <= nega_size and K <= posi_size:
        min = 1e9
        for i in range(K+1):
            if i == 0:
                min = abs(negatives[-K])
            elif i > 0 and i < K:
                ne = abs(negatives[-K+i])
                po = positives[i-1]
                min = calc(ne, po, min)
            elif i == K:
                tmp = positives[K-1]
                min = tmp if min > tmp else min

        return min

    if K > nega_size and K > posi_size:
        min = 1e9
        for i in range(N-K+1):
            ne = abs(x[i])
            po = x[K+i-1]
            min = calc(ne, po, min)

        return min

    if nega_size < K and K <= posi_size:
        min = 1e9
        for i in range(nega_size):
            po = x[K+i-1]
            ne = abs(x[i])
            min = calc(ne, po, min)

        min = abs(positives[K-1]) if abs(positives[K-1]) < min else min
        return min

    if posi_size < K and K <= nega_size:
        min = 1e9
        for i in range(posi_size):
            po = x[-i-1]
            ne = abs(x[-K-i])
            min = calc(po, ne, min)

        min = abs(negatives[-K]) if abs(negatives[-K]) < min else min
        return min


print(main())

Submission status: Accepted

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

d = []
for i in range(N - K + 1):
    left = xlist[i]
    right = xlist[i + K - 1]
    if right < 0:
        tmp_d = - left
    elif left > 0:
        tmp_d = right
    else:
        tmp_d = 2 * min(-left, right) + max(-left, right)
    d.append(tmp_d)

print(min(d))

Submission status: Accepted

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

sm = 10000000000000000
for i in range(N-K+1):
  #li[i+K-1]-li[i]
  a,b = li[i],li[i+K-1]
  if ( b<=0 ):
    sm = min (sm,-a)
  if ( a <= 0 and 0 <= b ):
    sm = min ( sm , b - 2*a )
    sm = min ( sm , 2*b - a )
  if ( a >= 0 ):
    sm = min ( sm , b)
print ( sm )

Submission status: Accepted

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

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

cumsum_candles = [0]
for i in range(1, len(candles)):
    cumsum_candles.append(candles[i] - candles[0])

zero_idx = 0
for i in range(len(candles)):
    if candles[i] <= 0:
        zero_idx = i

min_time = 10000000000000

low_itr = 0
up_itr = zero_idx

while low_itr <= up_itr and up_itr < len(candles):
    if up_itr-low_itr+1 > K:
        low_itr += 1
    elif up_itr-low_itr+1 < K:
        up_itr += 1
    else :
        time = cumsum_candles[up_itr] - cumsum_candles[low_itr]

        if zero_idx != low_itr or zero_idx != up_itr or K==1:
            min_time = min(min_time, time+abs(candles[up_itr]), time+abs(candles[low_itr]))
        else:
            min_time = min(min_time, time)

        low_itr += 1
        up_itr += 1

print min_time

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import bisect

N, K = map(int, input().split())
x = list(map(int, input().split()))
ans, tmp = 10**9, 10**9

#print(bisect.bisect(x, 0))

for i in range(len(x) - K + 1):
  if x[i] <= 0 and x[i+K-1] >= 0:
    tmp = abs(x[i]) + x[i+K-1] + min(abs(x[i]), x[i+K-1])
  elif x[i] < 0 and x[i+K-1] <= 0:
    tmp = abs(x[i])
  elif x[i] >= 0 and x[i+K-1] > 0:
    tmp = x[i+K-1]
#  elif i == bisect.bisect(x, 0)-1:
#    tmp = x[i+K-1]
#  elif i+K-1 == bisect.bisect(x, 0)-1:
#    tmp = abs[x[i]]
#  print("i:{}, i+K-1:{}, tmp:{}".format(i, i+K-1, tmp))
  ans = min(tmp, ans)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

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

min_cost = int(1e10)
for i in range(K, N+1):
    min_cost = min(min_cost, X[i-1] - X[i-K] + min(abs(X[i-1]), abs(X[i-K])))
    
print(min_cost)

Submission status: Accepted

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

a = []

for i in range(n-k+1):
    left = x[i]
    right = x[i+k-1]
    a.append(min(abs(left)+abs(right-left),abs(right)+abs(left-right)))

print(min(a))

Submission status: Accepted

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

min_t = 10 ** 9

import bisect

snuke = bisect.bisect_left(x, 0)
if snuke < n and x[snuke] == 0:
    k -= 1
    n -= 1
    del x[snuke]

for i in range(k+1):
    if i == 0:
        left = 0
    elif snuke - i >= 0:
        left = abs(x[snuke - i])
    else:
        left = 10 ** 9

    if k - i == 0:
        right = 0
    elif snuke + k - i - 1 <= n - 1:
        right = abs(x[snuke + k - i - 1])
    else:
        right = 10 ** 9

    min_t = min(min_t, min(left, right) * 2 + max(left, right))

print(min_t)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# 2019/05/10
# AtCoder Beginner Contest 107 - C

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

# Init
acdist = list()
#acdist.append(0) # Distance from x[0]
for i in range(n):
    wx = x[i] - min(x[0], 0)
    acdist.append(wx)

mindist = 10 ** 10
eflg = False

if x[0] >= 0:
    mindist = x[k-1]
    eflg = True
elif x[n-1] <= 0:
    mindist = abs(x[n-k])
    eflg = True

for i in range(n-k+1):
    if eflg == True:
        break
    sidx = i
    eidx = i + k - 1
    if (x[eidx] < 0 and eidx < n-1) or (x[sidx] > 0 and sidx > 0):
        continue
    else:
        # 折り返してゴールまで
        dist = acdist[eidx] - acdist[sidx]
        # 0からSidxまでの距離とEidxまでの距離の小さい方を足す
        dist += min(0-x[sidx], x[eidx]-0)
        if dist < mindist:
            mindist = dist

# Output
print(mindist)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
minus = []
minus.append(0)
plus = []
plus.append(0)

for n in x:
    if n < 0:
        minus.append(n)
    else:
        plus.append(n)
minus.sort(reverse=True)
totals = []

for i in range(len(minus)):
    if (k-i < len(plus)) and (k-i >= 0):
        if i == 0:
            totals.append(plus[k-i])
        else:
            totals.append(2 * abs(minus[i]) + plus[k-i])
            # print(i)
            # print(abs(minus[i]))
            # print(plus[k-i])
for i in range(len(plus)):
    if (k-i < len(minus)) and (k-i >= 0):
        if i == 0:
            totals.append(abs(minus[k-i]))
        else:
            totals.append(2 * plus[i] + abs(minus[k-i]))
# print(totals)
print(min(totals))

Submission status: Accepted

Solution code:
import sys

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

lst_p = []
lst_m = []
for i in range(N):
    if lst[i] == 0:
        K -= 1
    if lst[i] > 0:
        lst_p += [lst[i]]
    elif lst[i] < 0:
        lst_m += [lst[i]]


p = 0
m = 0
x, y = 0, len(lst_m)-1
lastx = len(lst_p)
lasty = len(lst_m)
#print (lastx, lasty)

def check(k):
    ans = 10 ** 9
    for j in range(0,k+1): #j: 正側の使う個数
#        print ('j, k-j', j, k-j)
        if j > lastx or k-j > lasty:
            pass
        else:
            if j == 0:
                p = 0
            else:
                p = lst_p[j-1]
            if k-j == 0:
                m = 0
            else:
                m = lst_m[lasty-(k-j)]
            ans = min(ans, 2 * p + abs(m), p + 2 * abs(m))
    return ans

print (check(K))

Submission status: Accepted

Solution code:
# 入力
n, k = map(int, input().split())
xs = list(map(int, input().split()))

if 0 in xs:
    xs.remove(0)
    k -= 1

puls = [x for x in xs if x > 0][:k]
minus = [x for x in xs[::-1] if x < 0][:k]
xs = minus[::-1] + [0] + puls
k += 1

crange = []
if len(minus) < len(puls):
    crange = [(len(xs)-p-k, len(xs)-p-1) for p in range(len(xs)-k+1)]
else:
    crange = [(p, p+k-1) for p in range(len(xs)-k+1)]

print(min([min(xs[c2]-2*xs[c1], 2*xs[c2]-xs[c1]) for c1, c2 in crange]))

Submission status: Accepted

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

# Kのwindowを持っている
# 正負で挙動が少し変わる
# +方向に進むか、-方向に進むか
ans = 10**10
for i in range(N-K+1):
    plus =  abs(X[i]) + abs(X[i+K-1]-X[i])
    minus = abs(X[i+K-1]) + abs(X[i+K-1]-X[i])
    ans = min(ans,plus,minus)
print(ans)