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())
xn = list(map(int, input().split()))
if 0 in xn:
  k -= 1
xm = [-1 * x for x in xn[::-1] if x < 0]
xp = [x for x in xn if x > 0]

if k == 0:
  print(0)
  exit()
elif len(xm) == 0:
  print(xp[k-1])
  exit()
elif len(xp) == 0:
  print(xm[k-1])
  exit()
  
if k > len(xm):
  nm = len(xm)
  np = k-len(xm)
  sm = xm[-1]
  sp = xp[np-1]
else:
  nm = k
  np = 0
  sm = xm[nm - 1]
  sp = 0
s_min = min(sm, sp) * 2 + max(sm, sp)

for i in range(min(k, len(xp), len(xm), n-k)):
  sm = xm[nm - i - 2]
  sp = xp[np + i]
  s_min = min(s_min, min(sm, sp) * 2 + max(sm, sp))
               
print(s_min)

Submission status: Accepted

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

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

def calc_time(x_max, x_min):
    if x_max * x_min >= 0:
        if abs(x_max) > abs(x_min):
            return x_max
        else:
            return abs(x_min)
    else:
        return x_max - x_min + min(abs(x_max), abs(x_min))

def calc_start_and_goal_position(index):
    if index - K >= 0:
        start_index = index - K
    else:
        start_index = 0
    
    if N > index + K + 1:
        goal_index = index + 1
    else:
        goal_index = N - K + 1
    
    return start_index, goal_index

if __name__ == "__main__":
    index = -1
    for i, x in enumerate(X):
        if x >= 0:
            index = i 
            break
    if index == -1:
        index = i
    start_index, goal_index = calc_start_and_goal_position(index)

    time_min = float('inf')
    for i in range(start_index, goal_index):
        time = calc_time(X[i+K-1], X[i])
        if time < time_min:
            time_min = time
    print(time_min)

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):
    # # ２点間の距離
    d1 = X[i + K - 1] - X[i]
    # # ０からの距離
    d2 = min(abs(X[i + K - 1]), abs(X[i]))
    ans = min(ans, d1 + d2)

print(ans)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc107/tasks/arc101_a
# C - Candles

n, k = list(map(int, input().split()))
x_list = list(map(int, input().split()))
x_list = sorted(x_list)
min_l = float('inf')

minus_list = [x for x in x_list if x < 0]
plus_index = len(minus_list)

for i, x in enumerate(x_list):
    left, right = x_list[i], x_list[i+k-1]
    # 最左端に行ってから、最右端に行く
    a = abs(left) + abs(left-right)
    # 最右端に行ってから、最左端に行く
    b = abs(right) + abs(right - left)
    l = min(a, b)

    if l < min_l:
        min_l = l

    if i + k > n - 1:
        break

print(min_l)

Submission status: Accepted

Solution code:
#### import ####
import sys
import math
from collections import defaultdict

#### 設定 ####
sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

from bisect import bisect_left

N,K = II()
x = III()
y = []
for i in range(N):
    if x[i]!=0:
        y.append(x[i])
    else:
        K -= 1
        N -= 1

minus = bisect_left(x,0)
ans = float('inf')

for i in range(min(minus+1,K+1)):
    if i==0: a=0
    else: a = y[minus-1-i+1]
    if K-i==0: b=0
    else:
        if minus+K-i-1<=N-1: 
            b = y[minus+K-i-1]
        else:
            continue
    temp = min(b-2*a,2*b-a)
    if temp<ans:
        ans = temp

print(ans)

Submission status: Accepted

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

T = []
for i in range(0, N-K+1):
  j = i + (K-1)
  # 座標x[i]から座標x[j]までのろうそくに火をつける
  if x[i] >= 0:
    T.append(abs(x[j]))
  elif x[j] <= 0:
    T.append(abs(x[i]))
  else: # x[i] < 0 < x[j]:
    T.append(abs(x[i]) + abs(x[j]) + min(abs(x[i]), abs(x[j])))

ans = min(T)
print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
X = list(map(int,input().split()))
res = 9999999999999
for i in range(N-K+1):
    ans_1 = abs(X[i]) + abs(X[i] - X[i+K-1])
    ans_2 = abs(X[i+K-1]) + abs(X[i] - X[i+K-1])
    res = min(res,min(ans_1,ans_2))
print(res)

Submission status: Accepted

Solution code:
import numpy as np

def solve(x, N, K):
    ans = 300000000
    for i in range(N - K + 1):
        x1 = x[i]
        x2 = x[i + K - 1]
        if x1 >= 0:
            ans = min(ans, x2)
        elif x2 <= 0:
            ans = min(ans, -x1)
        else:
            ans= min(ans, x2 - x1 + min(x2, -x1))
    return ans


stdin = open(0, 'rb')
pin = np.fromstring(stdin.read(), dtype=np.int64, sep=' ')
N, K = pin[:2]
x = pin[2:]
ans = solve(x, N, K)
print(ans)

Submission status: Accepted

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

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):
    left=x[i]
    right=x[i+k-1]

    if left<=0 and right<=0:
        dist=abs(left)
    elif left>=0 and right>=0:
        dist=right
    else:
        first=min(-left, right)
        dist=first+right-left
    
    ans=min(ans, dist)

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

ans = [0] * (N-K+1)

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

print(min(ans))

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    pos = []
    neg = []
    zero = []
    for x in map(int, input().split()):
        if x < 0: neg.append(x)
        elif x > 0: pos.append(x)
        else: zero.append(x)
    K -= len(zero)
    if K <= 0: return 0
    minT = float('inf')
    for i in range(K+1):
        dneg, dpos = 0, 0
        if i <= len(neg) and K-i <= len(pos):
            if i > 0:
                dneg = -neg[len(neg)-i]
            if K-i > 0:
                dpos = pos[K-i-1]
            minT = min([minT, 2*dneg+dpos, dneg+2*dpos])
    return minT

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

Submission status: Accepted

Solution code:
import math
import sys
import queue
from collections import Counter
from itertools import accumulate
from fractions import gcd
from functools import reduce


def lcm(a, b):
    return a * b // gcd(a, b)

def combination_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def permutations_count(n, r):
    return math.factorial(n) // math.factorial(n - r)

sys.setrecursionlimit(10000)

mod = 1000000007

"""
# 0埋め, 小数点出力桁指定時のときの出力
a = 100
b = 0.987654321
print("{0:06d}-{1:6f}".format(a,b))
000100-0.987654

# 文字列をリストに格納
char_list = list("abcd") # ["a","b","c","d"]

# 標準入力取得
## 文字列
    = sys.stdin.readline().rstrip()
    = list(sys.stdin.readline().rstrip())

## 数値
    = int(sys.stdin.readline())
    = map(int, sys.stdin.readline().split())
    = list(map(int, sys.stdin.readline().split()))
    = [list(map(int,list(sys.stdin.readline().split()))) for i in range(N)]
"""

if __name__ == "__main__":
    N, K = map(int, sys.stdin.readline().split())
    L = list(map(int, sys.stdin.readline().split()))

    ans = 10 ** 10
    for i in range(N - K + 1):
        left = i
        right = left + K - 1
        l_search = abs(L[left]) + abs(L[left] - L[right])
        r_search = abs(L[right]) + abs(L[left] - L[right])
        ans = min(ans, min(l_search, r_search))
    print(ans)

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):
    l = x[i]
    r = x[i+k-1]
    ans.append(min(abs(l) + abs(r-l), abs(r) + abs(l-r)))
print(min(ans))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
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 II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

def main(): 
    N, K = LI()
    x_li = LI()  # sorted

    from bisect import bisect_left
    zeropoint = bisect_left(x_li, 0)

    x_negative = [-x for x in reversed(x_li[:zeropoint])]
    x_positive = x_li[zeropoint:]

    # はじめに正の方向に動くとき：
    if len(x_positive) > 0:
        if len(x_positive) >= K:
            pos_right = K-1
            pos_left = 0
            min_moves = x_positive[pos_right]
        else:
            pos_right = len(x_positive) - 1
            pos_left = K - len(x_positive) - 1
            min_moves = x_negative[pos_left] + x_positive[pos_right] * 2
        i = 0
        while True:
            i += 1
            if pos_left + i >= len(x_negative) or pos_right-i < 0: break
            moves = x_negative[pos_left+i] + x_positive[pos_right-i] * 2
            min_moves = min(min_moves, moves)
    else:
        min_moves = INF

    # はじめに負の方向に動くとき：
    if x_positive and x_positive[0] == 0:
        x_positive = x_positive[1:]
        x_negative = [0] + x_negative
    x_positive, x_negative = x_negative, x_positive

    if len(x_positive) > 0:
        if len(x_positive) >= K:
            pos_right = K-1
            pos_left = 0
            min_moves = min(min_moves, x_positive[pos_right])
        else:
            pos_right = len(x_positive) - 1
            pos_left = K - len(x_positive) - 1
            min_moves = min(min_moves, x_negative[pos_left] + x_positive[pos_right] * 2)
        i = 0
        while True:
            i += 1
            if pos_left + i >= len(x_negative) or pos_right-i < 0: break
            moves = x_negative[pos_left+i] + x_positive[pos_right-i] * 2
            min_moves = min(min_moves, moves)
    else:
        pass


    print(min_moves)

main()

Submission status: Accepted

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

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

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

for i in range(n-k+1):
    l,r = X[i],X[i+k-1]
    if l<0 and r <=0:
        d = abs(l)
    elif l <=0 and r>=0:
        d = min(abs(l),abs(r))*2 + max(abs(l),abs(r))
    else:
        d = r
    min_d = min(min_d,d)
print(min_d)

Submission status: Accepted

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

    ans = float('inf')
    for i in range(N - K + 1):
        left = x[i]
        right = x[i + K - 1]
        dis = min(abs(left), abs(right)) + right - left
        ans = min(ans, dis)

    print(ans)



main()

Submission status: Accepted

Solution code:
def solve():
    n, k = map(int, input().split())
    xs = list(map(int, input().split()))
    min_dist = 10 ** 9
    for i in range(n - k + 1):
        length = abs(xs[i] - xs[i + k - 1])
        dist = min(abs(xs[i]) + length, abs(xs[i + k - 1]) + length)
        if dist < min_dist:
            min_dist = dist
    return min_dist


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

Submission status: Accepted

Solution code:
n, k= map(int,input().split())
x = list(map(int, input().split()))
if 0 not in x:
    k += 1
    x.append(0)
    x = sorted(x)
x = [abs(i) for i in x]

orig = x.index(0)

ans = float("inf")
for i in range(k):
    f = orig + i
    s = orig + i - k + 1
    if (s >= 0) and (f <= len(x)-1):
        temp1 = x[s]
        temp2 = x[f]
        ans = min([ans, 2*temp1+temp2, temp1+2*temp2])

print(ans)

Submission status: Accepted

Solution code:
n, k= map(int,input().split())
x = list(map(int, input().split()))
if 0 not in x:
    k += 1
    x.append(0)
    x = sorted(x)
x = [abs(i) for i in x]

orig = x.index(0)

ans = float("inf")
for i in range(k):
    f = orig + i
    s = orig + i - k + 1
    if (s >= 0) and (f <= n):
        temp1 = x[s]
        temp2 = x[f]
        ans = min([ans, 2*temp1+temp2, temp1+2*temp2])

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):
    x1, x2 = X[i], X[i + K - 1]
    if x2 <= 0:
        r = -x1
    elif x1 >= 0:
        r = x2
    else:
        r = min(2*x2 - x1, x2 - 2*x1)
    ans = min(ans, r)
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque

sys.setrecursionlimit(4100000)


def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def solve(N, K, inputs):
    candles = string_to_int(inputs[0])
    min_distance = -1
    for i in range(0, N-K+1):
        left = candles[i]
        right = candles[i+K-1]
        distance = 0
        if left <= 0 and right <= 0:
            distance = abs(left) - abs(right) + abs(0 - right)
        elif left >= 0 and right >= 0:
            distance = right
        else:
            if abs(right) > abs(left):
                distance = abs(left) + abs(left) + abs(right)
            else:
                distance = abs(right) + abs(right) + abs(left)
        if min_distance == -1 or min_distance > distance:
            min_distance = distance

    return min_distance


def string_to_int(string):
    return list(map(int, string.split()))


if __name__ == "__main__":
    [N, K] = string_to_int(input())
    ret = solve(N, K, inputs(1))
    print(ret)

Submission status: Accepted

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


def solve(N: int, K: int, x: "List[int]"):

    ans = 10000000000000000000


    al = []

    for i in range(N-K+1):
        if(x[i] <= 0 <= x[i+K-1]):
            w = abs(x[i+K-1]) + abs(x[i]) + min(abs(x[i+K-1]), abs(x[i]))
        else:
            w = max(abs(x[i+K-1]),abs(x[i]))
        
        al = [x[i], x[i+K-1]]
        ans = min(ans, w)
        
    if(not al):
        print(0)
    else:
        print(ans)

    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()))
a=[None]*(N-K+1)
for i in range(N-K+1):
    if x[i]<0 and x[i+K-1]>0:
        if x[i]+x[i+K-1]>0:
            a[i]=-2*x[i]+x[i+K-1]
        else:
            a[i]=-x[i]+2*x[i+K-1]
    elif x[i]>=0:
        a[i]=x[i+K-1]
    else:
        a[i]=-x[i]
print(min(a))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
l=list(map(int,input().split()))
m=0
zf=0
for i in range(n):
    if l[i]==0:
        zf=1
if zf==0:
    l.append(0)
    l.sort()
else:
    k-=1
if k==0:
    print(0)
    exit()
n=len(l)
pl=[]
nl=[]
for i in range(n):
    if l[i]==0:
        m=i
    elif l[i]>0:
        pl.append(l[i])
    else:
        nl.append(-l[i])
        
ans=1e10
for i in range(min(k-1,len(pl))):
    a=len(nl)-k+i+1
    if a>=0 and a<len(nl):
        ans=min(ans,2*pl[i]+nl[len(nl)-k+i+1])
for i in range(min(k-1,len(nl))):
    a=len(nl)-i-1
    b=k-i-2
    if b>=0 and b<len(pl):
        ans=min(ans,2*nl[a]+pl[k-i-2])
if k<=len(pl):
    ans=min(ans,pl[k-1])
if k<=len(nl):
    ans=min(ans,nl[len(nl)-k])
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):
    if abs(x[i]) > abs(x[i+k-1]):
        time = abs(x[i+k-1]) + abs(x[i] - x[i+k-1])
    else:
        time = abs(x[i]) + abs(x[i] - x[i+k-1])
    ans = min(ans, time)
print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
N,K=map(int,input().split())
#lx=[]
lx=list(map(int,input().split()))


for i in range(N-K+1):
    ansi=min(abs(lx[i])+lx[i+K-1]-lx[i],abs(lx[i+K-1])+lx[i+K-1]-lx[i])
    if i==0:
        ans=ansi
    else:
        ans=min(ans,ansi)
print(ans)

Submission status: Accepted

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


right_candle = [0] + [i for i in candle_list if i>0] + [float('inf')] * k
left_candle = [-float('inf')] * k + [i for i in candle_list if i<=0] + [0]


print(min([-left_candle[-i-1] * 2 + right_candle[k-i] for i in range(k+1)] + \
          [-left_candle[-i-1] + right_candle[k-i] * 2 for i in range(k+1)]))

Submission status: Accepted

Solution code:

def resolve():
    n, k = list(map(int, input().split()))
    xxx = list(map(int, input().split()))
    ans = float("inf")
    for i in range(n-k+1):
        max_l = xxx[i+k-1]
        min_l = xxx[i]
        if not min_l <= 0 <= max_l:
            ans = min(ans, max(abs(min_l), abs(max_l)))
        else:
            ans = min(ans, min(abs(min_l), abs(max_l))+abs(max_l-min_l))
    print(ans)
resolve()

Submission status: Accepted

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

Submission status: Accepted

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

mint = 1000000000

for i in range(n-k+1):
    l = x[i]
    r = x[i+k-1]
    if l >= 0:
        mint = min(mint,r)
    elif r <= 0:
        mint = min(mint,-l)
    else:
        d = min(-l+2*r,r-2*l)
        mint = min(mint,d)
print(mint)

Submission status: Accepted

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

res = 1e14
for l in range(N - K + 1):
    r = l + K - 1
    tmp = abs(X[r] - X[l])
    res = min(res, tmp + min(abs(X[r]), abs(X[l])))
print(res)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# 2019/08/10

from bisect import bisect_left

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

idx=bisect_left(x,0)
rn=n-idx
l=idx if rn>=k else idx-(k-rn)
r=l+k-1
ans=float('inf')

while 0<=l and idx<=r+1:
    if idx==l and r-l+2>=k:
        lf=float('inf')
        rf=x[r]
    elif idx==r+1 and r-l+2>=k:
        lf=abs(x[l])
        rf=float('inf')
    else:
        lf=abs(x[l])*2+x[r] 
        rf=x[r]*2+abs(x[l])
    ans=min(min(lf,rf),ans)

    l-=1;r-=1
print(ans)

Submission status: Accepted

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

ans = float('inf')

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

print(ans)

Submission status: Accepted

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

print(min(d))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
from bisect import bisect_left

def main():
	n, k = map(int, input().strip().split())
	x = list(map(int, input().strip().split()))
	# zero = bisect_left(x, 0)
	# print("zero:{}".format(zero))
	ans = 10**12
	for l in range(n):
		r = l + k - 1
		if r >= n:
			break
		if x[r] <= 0:
			ans = min(ans, abs(x[l]))
		elif 0 <= x[l]:
			ans = min(ans, abs(x[r]))
		else:
			ans = min(ans, min(2*abs(x[l])+x[r], 2*x[r]+abs(x[l])))
		# print("l:{}, r:{}, ans:{}".format(left_i, right_i, ans))
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
from bisect import bisect_left

def main():
	n, k = map(int, input().strip().split())
	x = list(map(int, input().strip().split()))
	zero = bisect_left(x, 0)
	# print("zero:{}".format(zero))
	ans = 10**12
	for l in range(k+1):
		r = k-l-1
		left_i = zero-l
		right_i = zero+r
		if left_i >= 0 and right_i < n:
			if x[left_i] >= 0:
				ans = min(ans, x[right_i])
			elif x[right_i] <= 0:
				ans = min(ans, abs(x[left_i]))
			else:
				ans = min(ans, min(2*abs(x[left_i])+x[right_i], 2*x[right_i]+abs(x[left_i])))
		# print("l:{}, r:{}, ans:{}".format(left_i, right_i, ans))
	print(ans)

if __name__ == '__main__':
	main()

Submission status: Accepted

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

minus = []
plus = []
for x in xarr:
    if x < 0:
        minus.append(x)
    else:
        plus.append(x)

ans = 0
if len(minus) == 0:
    ans = plus[k-1]
elif len(plus) == 0:
    ans = abs(minus[-k])
else:
    acm = [0]
    acp = [0]
    ans = 1000000000000000000000
    for i in range(len(minus)):
        acm.append(abs(minus[-i-1]))
    for i in range(len(plus)):
        acp.append(plus[i])

    for i in range(len(minus)+1):
        temp1 = 0
        temp2 = 0
        if i > k:
            break
        lest = k-i
        if lest > len(plus):
            continue
        temp1 = acm[i]*2+acp[lest]
        temp2 = acm[i]+acp[lest]*2
        t = min(temp1,temp2)
        # print(i,lest,temp1,temp2)
        if t < ans:
            ans= t
    # if k <= len(plus):
    #     t = plus[k-1]
    #     if t < ans:
    #         ans = t

print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
A=list(map(int,input().split()))
mini=100000000000000
for i in range(N-K+1):
    if A[i]<0 and A[i+K-1]>=0:
        if abs(A[i])>abs(A[i+K-1]):
            if mini>abs(A[i+K-1])*2+abs(A[i]):
                mini=abs(A[i+K-1])*2+abs(A[i])
        else:
            if mini > abs(A[i]) * 2 + abs(A[i+K-1]):
                mini = abs(A[i]) * 2 + abs(A[i+K-1])
    else:
       if mini>max(abs(A[i]),abs(A[i+K-1])):
           mini=max(abs(A[i]),abs(A[i+K-1]))
print(mini)

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):
    j = i + K - 1
    if x[i] <= 0 <= x[j]:
        t = x[j] - x[i] + min(x[j], -x[i])
    else:
        t = max(abs(x[i]), abs(x[j]))
    ans = min(ans, t)
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
x = list(map(int,input().split()))
proto = []
for i in range(n-k+1):
  left = x[i]
  right = x[i+k-1]
  al = abs(left)
  ar = abs(right)
  if left * right < 0:
    now = al + ar + min(al,ar)
  else:
    now = max(al,ar)
  proto.append(now)
print(min(proto))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
lst = list(map(int, input().split()))
ans = 10 ** 10
for i in range(N-K+1):
	left = lst[i]
	right = lst[i+K-1]
	if (abs(left) > abs(right)):
		dis = abs(left - right) + abs(right)
	else:
		dis = abs(left - right) + abs(left)
	if (dis < ans):
		ans = dis    
print(ans)

Submission status: Accepted

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

split_idx = None
for i,x in enumerate(x_list):
    if x >= 0:
        split_idx = i
        break
if split_idx == None:
    lefts = x_list
    rights = []
else:
    lefts = x_list[:split_idx]
    rights = x_list[split_idx:]

if len(rights)>0:
    if rights[0]==0:
        K -= 1
        rights = rights[1:]

if K == 0:
    print(0)
else:
    min_time = 10**9
    for left_cnt in range(K+1):
        right_cnt = K-left_cnt
        if left_cnt > len(lefts) or right_cnt > len(rights):
            continue
        if left_cnt ==0 and right_cnt == 0:
            tmp_time = 0
        elif left_cnt == 0:
            tmp_time = rights[right_cnt-1]
        elif right_cnt == 0:
            tmp_time = -lefts[-left_cnt]
        elif -lefts[-left_cnt] >= rights[right_cnt-1]:
            tmp_time = rights[right_cnt-1]*2 + (-lefts[-left_cnt])
        else:
            tmp_time = rights[right_cnt-1] + (-lefts[-left_cnt]) * 2
        if tmp_time < min_time:
            min_time = tmp_time
    print(min_time)

Submission status: Accepted

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

ans = float("inf")
for i in range(n-k+1):
    if i != 0:
        if l[i-1]>=0:
            continue
    if i != n-k:
        if l[i+k]<=0:
            continue

    if l[i]>=0:
        now = l[i+k-1]
    elif l[i+k-1]<=0:
        now = abs(l[i])
    else:
        now = min(abs(l[i])*2+l[i+k-1], abs(l[i])+l[i+k-1]*2)

    ans = min(ans, now)

print(ans)

Submission status: Accepted

Solution code:
from functools import reduce
import math

def main():
    # 文字列の2進数を数値にする
    # '101' → '5'
    # 文字列の頭に'0b'をつけてint()にわたす
    # binary = int('0b'+'101',0)

    # 2進数で立っているbitを数える
    # 101(0x5) → 2
    # cnt_bit = bin(5).count('1')
    
    # N! を求める
    # f = math.factorial(N)

    # N の逆元
    # N_inv = pow(N,MOD-2,MOD)

    # nCr
    # Nの階乗 * rの階乗の逆元 * n-rの階乗の逆元
    
    # 切り捨て
    # 4 // 3
    # 切り上げ
    #-(-4 // 3)
    
    # 初期値用:十分大きい数(100億)
    INF = float("inf")

    # 大きな素数
    MOD = 10**9+7
    
    # 1文字のみを読み込み
    # 入力:2
    # a = input().rstrip()
    # 変数:a='2'
    
    # スペース区切りで標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a, b, c, d = (int(_) for _ in input().split())  
    # 変数:a=2 b=4 c=5 d =7
    
    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a = list(int(_) for _ in input().split())
    # 変数:a = [2, 4, 5, 7]    

    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2457
    # a = list(int(_) for _ in input())
    # 変数:a = [2, 4, 5, 7]    
    N, K = (int(_) for _ in input().split())
    x = list(int(_) for _ in input().split())
    ans = INF
    for i in range(N-K+1):
        l = i
        r = i + K-1
        ans_l = abs(x[l]) + abs(x[l]-x[r])
        ans_r = abs(x[r]) + abs(x[l]-x[r])
        ans = min(ans_l,ans_r,ans)
        
    print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
x = list(map(int, input().split()))
ans = min(b - a + min(abs(a), abs(b)) for a, b in zip(x, x[K-1:]))
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys, math, fractions, itertools


def solve(N: int, K: int, x: "List[int]"):
    mn = 1e9
    for i in range(N-K+1):
        n = abs(x[i])
        a = abs(x[i+K-1])
        if x[i+K-1] * x[i] < 0:
            mn = min([mn, 2*a+n, 2*n+a])
        else:
            mn = min([mn, max(a, n)])
    print(mn)
    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:
import sys

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

ans = sys.maxsize

for i in range(N-K+1):
    minNum = candles[i]
    maxNum = candles[i+K-1]
    l = abs(minNum) + abs(minNum - maxNum)
    r = abs(maxNum) + abs(maxNum - minNum)
    ans = min(ans, min(l, r))

print(ans)

Submission status: Accepted

Solution code:
import bisect

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

idx = bisect.bisect_left(x,0)
"""
if x[idx] == 0:
    x.insert(idx,0)
"""
ans = 10**100


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

if idx == n:
    ans = -x[-k]

print(ans)

Submission status: Accepted

Solution code:

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

for i in range(n-k+1):
    l = lst[i]
    r = lst[i+k-1]
    way1 = abs(l) + abs(r-l)
    way2 = abs(r) + abs(l-r)
    m = min(way1,way2)
    if i==0:
        ans = m
    elif m < ans:
        ans = m
    
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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