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
# hello worldと表示する
#dpでできないかな？
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,k=MI()
lis=LI()
minus,plus=[],[]
for i in range(n):
    if lis[i]==0:
        k-=1
    elif lis[i]<0:
        minus.append(lis[i]*(-1))
    else:
        plus.append(lis[i])
minus=list(reversed(minus))
if k<=0:
    print(0)
    exit(0)
'''print(minus)
print(plus)'''
'''m=list(accumulate(minus))
p=list(accumulate(plus))'''
m=minus
p=plus
p=[0]+p
m=[0]+m
'''print(m)
print(p)'''
lens=[]

for i in range(k+1):
    im=i
    ip=k-i
    if im<len(m) and ip<len(p):
        dis=min(m[im],p[ip])*2+max(m[im],p[ip])
        lens.append(dis)
print(min(lens))

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

Submission status: Accepted

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

global_min = float('inf')
for i in range(N-K+1):
    left = i
    right = i+K-1
    #print(left, right)

    if 0 <= Xs[left]:
        local_min = Xs[right]
    elif Xs[right] <= 0:
        local_min = abs(Xs[left])
    else: # 先にマイナス側に行く場合と、先にプラス場合に行く場合がある。
        tmp1 = 2 * abs(Xs[left]) + Xs[right]
        tmp2 = abs(Xs[left]) + 2 * Xs[right]
        local_min = min(tmp1, tmp2)

    global_min = min(global_min, local_min)

if global_min == float('inf'):
    print(0)
else:
    print(global_min)

Submission status: Accepted

Solution code:
def main():
    from sys import setrecursionlimit, stdin
    from os import environ
    from collections import defaultdict, deque, Counter
    # from math import ceil, floor, gcd
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7

    N,K = LMIIS()
    X = LMIIS()


    #left:X[0] right:X[K-1]
    left = 0
    right = K-1
    syaku = X[right] - X[left]
    if abs(X[left]) > abs(X[right]):
        min_time = syaku + abs(X[right])
    else:
        min_time = syaku + abs(X[left])


    for i in range(N-K+1):
        syaku = X[right] - X[left]
        if abs(X[left]) > abs(X[right]):
            min_time = min(min_time, syaku + abs(X[right]))
        else:
            min_time = min(min_time, syaku + abs(X[left]))
        
        left += 1
        right += 1
    
    print(min_time)



    
main()

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
import copy
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

N, K = getNM()
X = getList()
ans = float('inf')

# 一直線に行くのが一番いいやり方
for i in range(N - K + 1):
    # もしX[i],X[i + K - 1]とも0以下の場合
    # 最短経路は0 ~ (X[i + K - 1]) ~ X[i]まで
    if X[i] <= 0 and X[i + K - 1] <= 0:
        ans = min(ans, -X[i])
    # もしX[i] < 0 <= X[i + K - 1]の場合
    # 最短経路は
    # X[i] ~ 0, 0 ~ X[i + K - 1]のうち近い方
    # + X[i] ~ X[i + K - 1]
    elif X[i] < 0 <= X[i + K - 1]:
        ans = min(ans, min(-X[i], X[i + K - 1]) + (X[i + K - 1] - X[i]))
    # もしX[i],X[i + K - 1]とも0以上の場合
    # 最短経路は0 ~ (X[i]) ~ X[i + K - 1]まで
    else:
        ans = min(ans, X[i + K - 1])
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
xlis = list(map(int, input().split()))
ret = 10 ** 100
for i in range(n-k+1):
    min_val = xlis[i]
    max_val = xlis[k+i-1]
    if min_val * max_val >= 0:
        tmp = max(abs(min_val), abs(max_val))
        ret = min(ret, tmp)
    else:
        fst = min(abs(min_val), abs(max_val))
        lst = max(abs(min_val), abs(max_val))
        tmp = fst * 2 + lst
        ret = min(ret, tmp)

print(ret)

Submission status: Accepted

Solution code:
def main():
    N, K = list(map(int, input().split(' ')))
    x = list(map(int, input().split(' ')))  # already sorted
    left = - min([x[0], 0])
    right = max([x[K - 1], 0])
    min_t = min([2 * left + right, left + 2 * right])
    for i in range(N):
        if i + K - 1 > N - 1:
            break
        left = - min([x[i], 0])
        right = max([x[i + K - 1], 0])
        min_t = min([min_t, min([2 * left + right, left + 2 * right])])
    print(min_t)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

ans = 10 ** 9

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

print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

n, k = map(int, input().split())
x = list(map(int, input().split()))
ans = 0
min_dis = 10 ** 20
a = 0
for i in range(n - k + 1):
    dis = x[i + k - 1] - x[i] + min(abs(x[i]), abs(x[i + k - 1]))
    if min_dis > dis:
        ans = dis
        min_dis = dis
print(ans)

Submission status: Accepted

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

is_zero = l.count(0)
K -= is_zero

if K:
    ans = float('inf')
    for i in range(N-K+1):
        lb, rb = l[i], l[i+K-1]
        steps = abs(rb-lb) + min(abs(rb), abs(lb))
        ans = min(ans, steps)

    print(ans)
else:
    print(0)

Submission status: Accepted

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i): is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res
## libs ##
from itertools import accumulate as acc, combinations as combi, product, combinations_with_replacement as combi_dup
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#
def main():
    n, k = MII()
    xx = MII()
    minv = 3*10**8
    for i in range(n-k+1):
        l = xx[i]
        r = xx[i+k-1]
        if l < 0 and r <= 0:
            minv = min(abs(l),minv)
            continue
        if l < 0 and r > 0:
            minv = min(min(abs(l),r)*2+max(abs(l),r), minv)
            continue
        if l >= 0:
            minv = min(r, minv)
            continue
    print(minv)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = tuple(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:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, k = map(int, readline().split())
x = list(map(int, readline().split()))
p = []
m = [0]
for i, xx in enumerate(x):
    if xx > 0:
        m += x[i:]
        break
    p.append(abs(xx))
p = [0] + p[::-1]
sizep = len(p) - 1
sizem = len(m) - 1
ans = float('inf')
for i in range(k):
    pp = k - i
    mm = i
    if sizep < pp:
        mm += pp - sizep
        pp = sizep
    if sizem < mm:
        pp += mm - sizem
        mm = sizem
    v = p[pp] + m[mm]
    if pp != 0 and mm != 0:
        v += min(p[pp], m[mm])
    ans = min(ans, v)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


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


def readint():
    return int(input())


def readnums():
    return map(int, input().split())


def readstrs():
    return input().split()


def main():
    N, K = readnums()
    x = list(readnums())
    ans = 0
    for i in range(K - 1, N):
        ls = i - K + 1
        le = i
        if x[ls] > 0:
            val = abs(x[le])
        elif x[le] < 0:
            val = abs(x[ls])
        else:
            val = abs(x[ls]) + abs(x[le])
            val += min(abs(x[ls]), abs(x[le]))
        if not ans:
            ans = val
        else:
            ans = min(ans, val)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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


res=3*10**8+1

for i in range(n-k+1):
	l=x[i]
	r=x[i+k-1]
	if l*r>=0:
		res=min(res,max(abs(l),abs(r)))
	else:
		res=min(res,abs(l)+abs(r)+min(abs(l),abs(r)))
	
print(res)

Submission status: Accepted

Solution code:
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)


inf = 10 ** 15
mod = 10 ** 9 + 7
n,k = map(int, input().split())
x = list(map(int, input().split()))
minus = []
plus = []
zind = bisect.bisect_left(x, 0)
if zind == n:
    minus = x
    minus.reverse()
else:
    minus = x[0:zind]
    minus.reverse()
    if x[zind] == 0:
        if k == 1:
            print(0)
            sys.exit()
        else:
            n-=1
            k-=1
            plus = x[zind+1:n]
    else:
        plus = x[zind:n]
lenp = len(plus)
lenm = len(minus)
ans = inf
if lenp >= k:
    ans = min(ans, plus[k-1])
if lenm >= k:
    ans = min(ans, abs(minus[k-1]))

for i in range(lenm):
    if 0 <= k-1-(i+1) < lenp:
        ans = min(ans, 2*abs(minus[i])+plus[k-1-(i+1)])
for i in range(lenp):
    if 0 <= k-1-(i+1) < lenm:
        ans = min(ans, 2 * plus[i] + abs(minus[k-1-(i+1)]))

print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
X = lr()
answer = []
for i in range(N-K+1):
    l = X[i]; r = X[i+K-1]
    a = abs(l) + abs(r-l)
    b = abs(r) + abs(l-r)
    answer.append(min(a, b))

print(min(answer))
# 03

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
from bisect import bisect_left, bisect_right

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
X = lr()
if 0 in X:
    K -= 1

i = bisect_left(X, 0)
ne = X[:i]
i = bisect_right(X, 0)
po = X[i:]
INF = 10 ** 10
neg = [INF] * (K+1)  # 左からK本選ぶ場合、K-1本選ぶ場合・・・0本選ぶ場合
neg[-1] = 0
pos = [INF] * (K+1)
pos[0] = 0
for j in range(len(ne)):
    if -j-2 < -K-1:
        break
    neg[-j-2] = ne[-j-1]

for j in range(len(po)):
    if j+1 > K:
        break
    pos[j+1] = po[j]

answer = INF
for j in range(K+1):
    x = abs(neg[j]); y = abs(pos[j])
    mi = min(x, y)
    ma = max(x, y)
    temp = mi * 2 + ma
    if temp < answer:
        answer = temp
print(answer)
# 52

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
data = list(map(int, input().split()))
l = 0
r = k - 1
ans = float("inf")
while True:
    if r == n:
        break
    ans = min(ans, abs(data[l]) + abs(data[l] - data[r]), abs(data[r]) + abs(data[r] - data[l]))
    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 i in range(N - K + 1):
    left = x[i]
    right = x[K - 1 + i]
    if left * right >= 0:
        ans = min(ans, max(abs(left), abs(right)))
    else:
        ans = min(ans, min(abs(left), abs(right)) + abs(left - right))
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 = x[i]
    r = x[i+k-1]
    if l*r >= 0:
        ans = min(ans,max(abs(r),abs(l)))
    elif l*r < 0:
        ans = min(ans,r-l + min(abs(r),abs(l)))
print(ans)

Submission status: Accepted

Solution code:
cand_num, tenka = map(int, input().split(" "))
candles = list(map(int, input().split(" ")))
mini = 10 ** 9

for i in range(cand_num - tenka + 1):
    if candles[i] * candles[tenka + i - 1] >= 0:
        temp = max(abs(candles[i]), abs(candles[tenka + i - 1]))
    else:
        temp = min(abs(candles[i]), abs(candles[tenka + i- 1])) * 2 + max(abs(candles[i]), abs(candles[tenka + i - 1]))
    mini = temp if mini > temp else mini
print(mini)

Submission status: Accepted

Solution code:
n, k, *a = map(int, open(0).read().split())
m = INF = float("inf")
for i in range(n - k + 1):
    l, r = a[i], a[i + k - 1]
    c = abs(r-l)
    m = min(m, min(abs(l) + c, abs(r) + c))
print(m)

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):
  ans = min(ans, max(0, -x[i]) + max(0, 2 * x[i + k - 1]),
            max(0, -2 * x[i]) + max(0, x[i + k - 1]))
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

X_n = sorted([-x for x in X if x < 0])
X_p = sorted([x for x in X if x >= 0])

ans = 10**20
for k in range(K+1):
    if len(X_n) >= k and len(X_p) >= K-k:
        if k == 0:
            ans = min(ans, X_p[K-1])
        elif k == K:
            ans = min(ans, X_n[K-1])
        else:
            ans = min(ans, 2*X_n[k-1] + X_p[K-k-1], X_n[k-1] + 2*X_p[K-k-1])
print(ans)

Submission status: Accepted

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

#from bisect import bisect_left

#p0 = bisect_left(x, 0)
#x[p0] == 0
ans = 10 ** 10
for i in range(n-k+1):
    ans = min(ans, abs(x[i]) + abs(x[i+k-1] - x[i]))
    ans = min(ans, abs(x[i+k-1]) + abs(x[i+k-1] - x[i]))
    #print(i, i+k-1, ans)
print(ans)

Submission status: Accepted

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

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, k = mi()
    L = lmi()
    ans = 2 ** 64 - 1
    for i in range(n - (k - 1)):
        if L[i+k-1] <= 0:
            cost = abs(L[i])
        elif L[i] >= 0:
            cost = L[i+k-1]
        else:
            cost = L[i+k-1] - L[i] + min(abs(L[i]), L[i+k-1])
        ans = min(ans, cost)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
from bisect import bisect
def main():
    n,k=map(int,input().split())
    X=list(map(int,input().split()))
    zero=bisect(X,0)
    ans=10**9
    for i in range(k+1):
        if zero-i<0 or zero+k-i-1>=n:
            continue
        if i==0:
            ans=min(ans,X[zero+k-i-1])
        elif i==k:
            ans=min(ans,-X[zero-i])
        else:
            kyori_m=2*-X[zero-i]+X[zero+k-i-1]
            kyori_p=-X[zero-i]+2*X[zero+k-i-1]
            ans=min(ans,kyori_m,kyori_p)  
    print(ans)

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
X=list(map(int,input().split()))
import numpy as np
a=np.searchsorted(X, 0, side='left')
if a==N:
  X=np.insert(X,a,0)
  N+=1
  K+=1
elif X[a]!=0:
  X=np.insert(X,a,0)
  N+=1
  K+=1
ans=10**18
i=a-K+1 if K-1<a else 0
while i<=a and i+K-1<N:
  l=-X[i]
  r=X[i+K-1]
  if l>r:
    l,r=r,l
  ans=min(ans,2*l+r)
  i+=1
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

ans = 10 ** 9
i = bisect_left(x_list, 0)
for j in range(max(i - k, 0), min(i + 1, n - k + 1)):
    if j == i - k:
        temp = abs(x_list[j])
    elif j == i:
        temp = x_list[j + k - 1]
    else:
        temp = x_list[j + k - 1] - x_list[j] + min(-x_list[j], x_list[j + k - 1])
    
    if temp < ans:
        ans = temp
print(ans)

Submission status: Accepted

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

def calc_distance(check_X):
    if check_X[0] * check_X[-1] < 0:
        result = min(abs(check_X[0]*2)+abs(check_X[-1]), abs(check_X[0])+abs(check_X[-1]*2))
    else:
        result = max(abs(check_X[0]),abs(check_X[-1]))
    return result

ans = calc_distance(check_X)

for i in range(K, len(X)):
    check_X.pop(0)
    check_X.append(X[i])
    ans = min(ans, calc_distance(check_X))

print(ans)

Submission status: Accepted

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from fractions import gcd
from math import factorial, sqrt, ceil
from functools import lru_cache, reduce
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def is_prime(n):
    if n == 1:
        return False
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            return False
    return True


# ワーシャルフロイド (任意の2頂点の対に対して最短経路を求める)
# 計算量n^3 (nは頂点の数)
def warshall_floyd(d, n):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d


# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定



# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
n, k = map(int, input().split())
x = list(map(int, input().split()))
a = []
b = []
ans = INF
for i in x:
    if i < 0:
        a.append(- i)
    elif i == 0:
        k -= 1
    else:
        b.append(i)
a = a[::-1]
# print("a =", a)
# print("b =", b)
for i in range(k + 1):
    if i > len(a) or k - i > len(b):
        continue
    cnt1 = 0
    cnt2 = 0
    if i != 0:
        cnt1 = a[i - 1]
    if i != k:
        cnt2 = b[k - i - 1]
    total = min(cnt1, cnt2) * 2 + max(cnt1, cnt2)
    # print("total =", total)
    ans = min(ans, total)
print(ans)

Submission status: Accepted

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

ptns = []
for i in range(n-k+1):
    ptns.append(abs(0 -l[i]) + abs(l[i] - l[i+k-1]))
    ptns.append(abs(0 -l[i+k-1]) + abs(l[i+k-1] - l[i]))

print(min(ptns))

Submission status: Accepted

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

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

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

ans = float('inf')
for i in range(n - k + 1):
    l = nums[i]
    r = nums[i + k - 1]
    if l >= 0:
        t = r
    elif r <= 0:
        t = abs(l)
    else:
        t = min(abs(l), abs(r)) * 2 + max(abs(l), abs(r))
    ans = min(ans, t)

print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
x = list(map(int,input().split()))
INF = 3*10**8+1

x_plus,x_minus,x_zero = [],[],0
for i in range(N):
    if x[i] < 0:
        x_minus.append(x[i])
    elif x[i] == 0:
        x_zero += 1
    else:
        x_plus.append(x[i])
for i in range(len(x_minus)//2):
    x_minus[i],x_minus[len(x_minus)-i-1] = x_minus[len(x_minus)-i-1],x_minus[i]

ans = INF
if 0 <= K-1-x_zero and K-1-x_zero < len(x_plus):
    ans = min(ans,x_plus[K-1-x_zero])
if 0 <= K-1-x_zero and K-1-x_zero < len(x_minus):
    ans = min(ans,-x_minus[K-1-x_zero])
for i in range(K):
    if i < len(x_plus) and 0 <= K-i-2-x_zero and K-i-2-x_zero < len(x_minus):
        tmp1 = 2*x_plus[i]-x_minus[K-i-2-x_zero]
        tmp2 = x_plus[i]-2*x_minus[K-i-2-x_zero]
        ans = min(ans,tmp1,tmp2)
if ans == INF:
    ans = 0
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
x = list(map(int,input().split()))
flag = True
for i in range(n+1):
    if i == n or x[i] > 0:
        x.insert(i,0)
        zahyou = i
        break
ans = 10**18
for i in range(k+1):
    flag = True
    if zahyou + i < n+1 and zahyou -k+i >= 0:
        mainasu = x[zahyou]-x[zahyou-k+i]
        purasu = x[zahyou+i]-x[zahyou]
        if mainasu != 0 and purasu != 0:
            purasu += min(mainasu,purasu)
        ans = min(ans,mainasu+purasu)
print(ans)

Submission status: Accepted

Solution code:
def main():
  import bisect
  n,k=map(int,input().split())
  x=list(map(int,input().split()))
  ans=abs(x[0])*2+abs(x[-1])*2
  if 0 in x:
    r=x.index(0)
    l=max(0,r-(k-1))
  else:
    r=bisect.bisect_right(x,0)
    l=max(0,r-k)
  ans=2*abs(x[0])+2*abs(x[-1])
  for i in range(l,min(n-k+1,r+1)):
    if x[i]*x[i+k-1]<=0:
      a=min(abs(x[i]),abs(x[i+k-1]))
      b=max(abs(x[i]),abs(x[i+k-1]))
      ans=min(ans,2*a+b)
    else:
      b=max(abs(x[i]),abs(x[i+k-1]))
      ans=min(ans,b)
  print(ans)
if __name__=='__main__':
  main()

Submission status: Accepted

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

minus = []
plus = []

for x in X:
    if x < 0:
        minus.append(-x)
    else:
        plus.append(x)

minus.reverse()
ans = float('inf')


for i in range(min(K+1, len(minus)+1)):
    p = K - i
    if i == 0:
        if len(plus) >= p:
            ans = min(ans, plus[K-1])
    elif i == K:
        if len(minus) >= K:
            ans = min(ans, minus[K-1])
    else:
        if len(plus) >= p and len(minus) >= i:
            a = plus[p-1]
            b = minus[i-1]
            if a < b:
                ans = min(ans, 2 * a + b)
            else:
                ans = min(ans, b * 2 + a)

print(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):
    lef = x[i]
    rig = x[i+K-1]
    ans = min(ans, abs(lef)+abs(rig-lef), abs(rig)+abs(rig-lef))
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):
    st=x[i]
    ed=x[i+k-1]
    
    if ed<=0:
        ans=min(ans,abs(st))
    elif st>=0 and ed>=0:
        ans=min(ans,ed)
    else:
        t=(min(abs(st),ed)*2)+max(abs(st),ed)
        ans=min(t,ans)

print(ans)

Submission status: Accepted

Solution code:
import bisect
n,k = map(int,input().split())
x = list(map(int,input().split()))
zero = bisect.bisect(x,0)
left = [0] + (x[:zero])[::-1]
right = [0] + x[zero:]
ans = 10**12
for i in range(min(k+1,len(left))):
  j = k-i
  if j >= len(right):
    continue
  ans = min(ans,2*right[j]-left[i],-2*left[i]+right[j])
print(ans)