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:
def solve():

    N, K = [int(i) for i in input().split()]
    xlist = [int(i) for i in input().split()]

    cost = float("inf")
    # 連続する組み合わせの数
    for i in range(N-K+1):
        # iが左端でjが右端
        j = i + K - 1
        cost = min(
            cost,
            # 左から進んだ場合
            abs(xlist[i]) + abs(xlist[j] - xlist[i]),
            # 右から進んだ場合
            abs(xlist[j]) + abs(xlist[i] - xlist[j])
        )
    print(cost)


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
def solve():

    N, K = [int(i) for i in input().split()]
    xlist = [int(i) for i in input().split()]

    cost = float("inf")
    for i in range(N-K+1):
        j = i + K - 1
        cost = min(
            cost,
            abs(xlist[i] - 0) + abs(xlist[j] - xlist[i]),
            abs(xlist[j] - 0) + abs(xlist[i] - xlist[j])
        )
    print(cost)


if __name__ == "__main__":
    solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
xs = list(map(int, input().split()))
xs.append(xs[-1])
ans = float('inf')
anses = []
for i in range(N-K+1):
    tmp = (abs(xs[i+K-1] - xs[i]))
    if xs[i]*xs[i+K-1] < 0 or xs[i] > 0 or xs[i+K-1] < 0: 
        tmp += min(abs(xs[i]), abs(xs[i+K-1]))
    anses.append(tmp)
    if ans > tmp:
        ans = tmp
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
M = float('inf')
for i in range(N-K+1):
    l = X[i]
    r = X[i+K-1]
    if l * r >= 0:
        M = min(max(abs(l), abs(r)), M)
    else:
        M = min(M, min(abs(l), abs(r)) * 2 + max(abs(l), abs(r)))
print(int(M))

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

Submission status: Accepted

Solution code:
def main():
    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
    #from itertools import product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    #from operator import itemgetter

    #inf = 10**17
    #mod = 10**9 + 7

    n,k = map(int, input().split())
    x = list(map(int, input().split()))
    p, n = [], []
    for i in x:
        if  i > 0:
            p.append(i)
        elif i < 0:
            n.append(-i)
    p.sort()
    n.sort()
    lenp = len(p)
    lenn = len(n)
    if lenp == 0 and lenn == 0:
        print(0)
        exit()
    if lenn == 0:
        print(p[k-1])
        exit()
    if lenp == 0:
        print(n[k-1])
        exit()
    res = 10000000000000000000000
    if lenp > lenn:
        for i in range(k-lenp-1, lenn):
            res = min(res, n[i]+p[k-i-2]+min(n[i], p[k-i-2]))
        print(res)
    else:
        for i in range(k-lenn-1, lenp):
            res = min(res, p[i]+n[k-i-2]+min(p[i], n[k-i-2]))
        print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

ans = 10**9+7

for i in range(N-K+1):
    left = x[i]
    right = x[i+K-1]
    time = min(abs(right),abs(left))+abs(right-left)
    ans = min(ans,time)
    
print(ans)

Submission status: Accepted

Solution code:
def main():
    n, k, *x = map(int, open(0).read().split())
    l = x[k - 1] - x[0] + min(abs(x[k - 1]), abs(x[0]))

    for i, j in zip(x, x[k - 1:]):
        y = j - i + min(abs(i), abs(j))
        if y - l < 0:
            l = y

    print(l)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    n, k, *x = map(int, open(0).read().split())
    d = 2 * 10 ** 9
    for i, j in zip(x, x[k - 1:]):
        d = min(d, j - i + min(abs(i), abs(j)))
    print(d)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    n, k, *x = map(int, open(0).read().split())
    d= []
    for i, j in zip(x, x[k - 1:]):
        y = j - i + min(abs(i), abs(j))
        d.append(y)
    print(min(d))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    n, k, *x = map(int, open(0).read().split())
    l = x[0 + k - 1] - x[0] + min(abs(x[0 + k - 1]), abs(x[0]))

    for i, j in zip(x, x[k - 1:]):
        y = j - i + min(abs(i), abs(j))
        if y < l:
            l = y

    print(l)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    n, k, *x = map(int, open(0).read().split())
    x = tuple(x)
    l = x[0 + k - 1] - x[0] + min(abs(x[0 + k - 1]), abs(x[0]))

    for i in range(n - k + 1):
        y = x[i + k - 1] - x[i] + min(abs(x[i + k - 1]), abs(x[i]))
        if y < l:
            l = y

    print(l)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    n, k, *x = map(int, open(0).read().split())
    l = x[0 + k - 1] - x[0] + min(abs(x[0 + k - 1]), abs(x[0]))

    for i in range(n - k + 1):
        y = x[i + k - 1] - x[i] + min(abs(x[i + k - 1]), abs(x[i]))
        if y < l:
            l = y

    print(l)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    n, k, *x = map(int, open(0).read().split())
    f = lambda i: x[i + k - 1] - x[i] + min(abs(x[i + k - 1]), abs(x[i]))
    l = f(0)

    for i in range(n - k + 1):
        y = f(i)
        if y < l:
            l = y

    print(l)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, minimum_spanning_tree
from scipy.sparse import csr_matrix, coo_matrix, lil_matrix
import numpy as np
from functools import reduce

from collections import deque, Counter, defaultdict
from itertools import product, permutations,combinations
from operator import itemgetter
from heapq import heappop, heappush
from bisect import bisect_left, bisect_right, bisect
from fractions import gcd
from math import ceil,floor, sqrt, cos, sin, pi, factorial
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**8)
INF = float('inf')
MOD = 10**9+7

def main():
  n, k = map(int, readline().split())
  x = list(map(int, readline().split()))
  ans = INF
  for i in range(n-k+1):
    if x[i]<0 and x[i+k-1]<0:
      ans = min(ans, abs(x[i]))
    elif x[i]<=0 and x[i+k-1]>=0:
      ans = min(ans, 2*abs(x[i])+x[i+k-1],abs(x[i])+2*x[i+k-1])
    else:
      ans = min(ans, x[i+k-1])
  print(ans)
  
  
  
  
  
if __name__ == '__main__':
  main()

Submission status: Accepted

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

Submission status: Accepted

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

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

ans=10**9
for i in range(N-K+1):
  L=A[i]
  R=A[i+K-1]
  ans=min(ans, R-L+min(abs(R), abs(L)))
  
print(ans)

Submission status: Accepted

Solution code:
mod = 10 ** 9 + 7
mod2 = 2**61+1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

def iip(listed=True):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iip_ord():
    return [ord(i) - ord("a") for i in input()]


def main():
    ans = solve()
    if ans is not None:
        print(ans)

def solve():
    N, K = iip(False)
    X = iip()

    A1 = [i for i in X if i > 0]
    A2 = [-i for i in X if i < 0]
    A2.sort()
    if 0 in X:
        K -= 1
        if K == 0:
            return 0

    ans = 10**50

    if K == 1:
        return min(A1[0], A2[0])

    for i in range(N):
        i1 = i-1
        i2 = K-i-1

        #print(i1, i2, len(A1), len(A2))
        #print(A1, A2)
        if i1 < -1 or i2 < -1 or i1 >= len(A1) or i2 >= len(A2):
            continue

        if i1 == -1:
            a = 0
        else:
            a = A1[i1]

        if i2 == -1:
            b = 0
        else:
            b = A2[i2]

        ans = min(ans, a*2+b, b*2+a)

    try:
        ans = min(A1[K-1], ans)
    except:
        pass

    try:
        ans = min(A2[K-1], ans)
    except:
        pass

    #print(A1)
    #print(A2)
    print(ans)


#####################################################ライブラリ集ここから

def YesNo(s):
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):
    for i in s:
        print(i)

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p, mod_= mod):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

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):
    cand = x[i + k - 1] - x[i] + min(abs(x[i + k - 1]), abs(x[i]))
    ans = min(ans, cand)

print(ans)

Submission status: Accepted

Solution code:
def Candles(n , k , xl):

    ans = 10**9

    for i in range(n - k + 1):
        lr = min(abs(xl[i]) + abs(xl[i] - xl[i + k - 1]) , abs(xl[i + k - 1]) + abs(xl[i + k - 1] - xl[i]))
        ans = min(ans , lr)

    return ans

def main():
    n , k = map(int , input().split())
    xl = list(map(int , input().split()))
    print(Candles(n , k , xl))

if __name__ == '__main__':
    main()

Submission status: Accepted

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


max = 10000000000000000000000000
for i in range(N - K + 1):
    # i = 0
    diff = X[i + K - 1] - X[i]
    t_1 = abs(X[i])
    t_1 += diff
    t_2 = abs(X[i + K - 1])
    t_2 += diff

    if t_1 < max:
        max = t_1
    if t_2 < max:
        max = t_2

print(max)

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    X = list(map(int, input().split()))
    D = [0]*(N - 1)
    for i in range(1, N):
        D[i-1] = X[i] - X[i - 1]
    ans = 0
    t = 0
    T = [0]*(N - K + 1)
    for i in range(1, N):
        t += D[i-1]
        if i < K:
            if i == K - 1:
                T[0] = t
            continue
        t -= D[i - K]
        T[i - K + 1] = t
    # print(D, T)
    ans = K * 10**8
    for i in range(N - K + 1):
        a = T[i] + min(abs(X[i]), abs(X[i + K - 1]))
        ans = min(a, 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 = 10 ** 16
for i in range(n-k+1):
    if x[i] * x[i+k-1] < 0:
        dis = min(abs(x[i]), abs(x[i+k-1])) * 2 + max(abs(x[i]), abs(x[i+k-1]))
    else:
        dis = max(abs(x[i]), abs(x[i+k-1]))
    ans = min(ans, dis)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value

def calc_min(a, b):
    if a>=0 and b>=0:
        return a
    elif a<0 and b<0:
        return abs(b)
    else:
        return 0

N, K = mi()
x = li()
ans = 10**13 + 1
'''
sum_k = X[K-1] - X[0]
min_k = calc_min(x[0], x[K-1])
ans = sum_k
print(sum_k)
for i in range(1, N-K+1):
    sum_k -= abs(x[i-1]) + min_k
    sum_k += abs(x[K-1+i])
    min_k = calc_min(x[i], x[K-1+i])
    sum_k += min_k
    print(sum_k)
    ans = min(ans, sum_k)

print(ans)
'''

for i in range(N-K+1):
    #sum_k = x[K-1+i] - x[i] + calc_min(x[i], x[K-1+i])
    sum_k = x[K-1+i] - x[i] + min(abs(x[i]), abs(x[K-1+i]))
    #min_k = calc_min(N[i], N[K-1+i])
    #sum_k += min_k
    #print(sum_k)
    ans = min(ans, sum_k)

print(ans)

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, acos, atan, asin, log, log10
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
def input(): return sys.stdin.readline().strip()
def STR(): return input()
def INT(): return int(input())
def FLOAT(): return float(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 9)
inf = sys.maxsize
mod = 10 ** 9 + 7
dx = [0, 0, 1, -1, 1, -1, -1, 1]
dy = [1, -1, 0, 0, 1, -1, 1, -1]

n, k = MAP()
x = LIST()
d = [x[i + k - 1] - x[i] + min(abs(x[i] - 0), abs(x[i + k - 1] - 0)) for i in range(n - k + 1)]
print(min(d))

Submission status: Accepted

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

Submission status: Accepted

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,k = LI()
x = LI()
ans = inf
for i in range(k,n+1):
    l,r = x[i-k],x[i-1]
    if l <= 0 and r <= 0:
        ans = min(ans, abs(l))
    elif l <= 0 and r > 0:
        ans = min(ans, 2*r+abs(l))
        ans = min(ans, 2*abs(l)+r)
    elif l > 0 and r > 0:
        ans = min(ans,r)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
x = [int(i) for i in input().split()]
a=[]
for i in range(N-K+1):
  left =x[i]
  right =x[i+K-1]
  p1 = abs(left) + abs(right-left)
  p2 = abs(right) + abs(right-left)
  p = min(p1,p2)
  a.append(p)
  
  
print(min(a))

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


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


def S(): return input()


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
# sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']


# show_flg = True
show_flg = False


def main():
    N, K = MI()
    x = LI()
    x.append(0)
    x.sort()

    for i in range(N+1):
        if x[i] == 0:
            zero_index = i

    ans = 10**9

    for i in range(N+1):
        # print(i, zero_index, i <= zero_index, zero_index <= i + K + 1)
        if i <= zero_index and zero_index <= i + K and i + K < N + 1:
            # print(x[i:i+K+1])
            left = x[i]
            right = x[i+K]
            mn = min(abs(left), abs(right))
            ans = min(ans, abs(left) + abs(right) + mn)
            # print(left, right)
            # print(ans)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

ret = 10**20

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

print(ret)

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()
elif x[n - 1] < 0:
    print(abs(x[n - k]))
    exit()
else:
    for i in range(n):
        if x[i] >= 0:
            ori = i
            break

f_inf = float("inf")
res = f_inf
for i in range(max(ori - k, 0), min(ori + k, n) - k + 1):
    time = min(abs(x[i + k - 1] - x[i]) + abs(x[i + k - 1]), abs(x[i]) + abs(x[i + k - 1] - x[i]))
    res = min(res, time)

print(res)

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):
  ans=min(ans,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:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n,k=mii()
arr=limii()
ans=10**1000
for i in range(n-k+1):
    ans=min(ans, abs(arr[i])+abs(arr[i]-arr[i+k-1]),abs(arr[i+k-1])+abs(arr[i]-arr[i+k-1]))
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
X, Y = [], []
for x in map(int, input().split()):
    if x < 0:
        X.append(-x)
    else:
        Y.append(x)
X.reverse()
INF = 10**9
ans = INF
if len(X) == 0:
    ans = Y[k-1]
elif len(Y) == 0:
    ans = X[k-1]
else:
    for i in range(1, k):
        L, R = k-i-1, i-1
        if not(L < len(X) and R < len(Y)):
            continue
        a, b = X[L], Y[R]
        ans = min(ans, min(a, b)+a+b)
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
X = []
Y = []
for x in map(int, input().split()):
    if x < 0:
        X.append(x)
    else:
        Y.append(x)
X.reverse()
INF = 10**9
ans = INF
if len(X) == 0:
    ans = Y[k-1]
elif len(Y) == 0:
    ans = X[k-1]*(-1)
else:
    for i in range(k):
        L = k-i-1
        R = i-1
        if L >= len(X) or R >= len(Y):
            continue
        a = X[L]*(-1)
        b = Y[R]
        ans = min(ans, min(a, b)+a+b)
print(ans)

Submission status: Accepted

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


m=10**9
for i in range(N-K+1):
    temp=x[i+K-1]-x[i]+min(abs(x[i+K-1]), abs(x[i]))
    #print(x[i+K-1], x[i], temp)
    if temp<m:
        m=temp
print(m)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
from decimal import *


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        res = []
        i = 1
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                res.append(i)
                if i != n // i:
                    res.append(n // i)
        return res

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

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


def pop_count(x):
    x = x - ((x >> 1) & 0x5555555555555555)
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    x = x + (x >> 32)
    return x & 0x0000007f


MOD = int(1e09) + 7
INF = int(1e15)


def main():
    # sys.stdin = open("sample.txt")
    N, K = Scanner.map_int()
    X = Scanner.map_int()
    ans = INF
    for l in range(N - K + 1):
        r = l + K - 1
        if X[l] <= 0 and X[r] <= 0:
            ans = min(ans, abs(X[l]))
        elif X[l] >= 0 and X[r] >= 0:
            ans = min(ans, abs(X[r]))
        else:
            ans = min(ans, abs(X[l]) * 2 + abs(X[r]))
            ans = min(ans, abs(X[r]) * 2 + abs(X[l]))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import bisect
import sys

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

index = bisect.bisect_left(x,0)

if x[0] >= 0 :
  print(x[k-1])
  sys.exit()
  
if x[-1] <= 0 :
  print(x[n-k]*(-1))
  sys.exit()

ans = 10**9
if min(index+k,n) == index+k :
  ans = x[index+k-1]

if max(0,index-k) == index - k :
  ans = min(ans,x[index-k]*(-1))
  
c = 0
for i in range(index,min(index+k,n)) :
  c += 1
  if i <= n-1 and i-(k-1) <= n-1 and i-(k-1) >= 0 :
    ans = min(ans,x[i]*2+x[i-(k-1)]*(-1))

c = 0
for i in range(max(0,index-k),index) :
  c += 1
  if i <= n-1 and i+(k-1) <= n-1 :
    ans = min(ans,x[i]*(-1)*2+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**9
for i in range(n-k+1) :
  xs = abs(x[i+k-1]-x[i])
  ans = min(ans,xs+abs(x[i]),xs+abs(x[i+k-1]))
  
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
n,k=map(int,input().split())
x=list(map(int,input().split()))
x_pos=list(filter(lambda x: x>=0,x))
x_neg=list(filter(lambda x:x<0,x))
x_neg=list(map(lambda x: -x , x_neg))
x_pos.sort()
x_neg.sort()
#print(x)
#print(x_pos)
#print(x_neg)
ans=float('inf')
if k<=len(x_pos):
    ans=min(ans,x_pos[k-1])
if k<=len(x_neg):
    ans=min(ans,x_neg[k-1])
for i in range(len(x_pos)):
    if k-2-i<len(x_neg) and k-2-i>=0:
        ans=min(ans,2*x_pos[i]+x_neg[k-2-i],2*x_neg[k-2-i]+x_pos[i])
print(ans)

Submission status: Accepted

Solution code:
def resolve():
    N, K = map(int, input().split(" "))
    Xs = list(map(int, input().split(" ")))
    ans = 10**9
    for i in range(N-K+1):
        cnt = Xs[i+K-1] - Xs[i] + min(abs(Xs[i+K-1]), abs(Xs[i]))
        ans = min(cnt, ans)
    print(ans)



if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
N, K = map(int, raw_input().split())
x = map(int, raw_input().split())
ans = 10**9
for y in range(N-K+1):
    left = x[y]
    right = x[y+K-1]
#    print left, right                                                                                                                                    

    if left < 0 and right <= 0:
        ans = min(ans, -left)
    elif left <= 0 and right >= 0:
        ans = min(ans, -2*left+right, -left+2*right)
    else:
        ans = min(ans, right)

if ans == 10**9:
    print 0
else:
    print ans

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
s, t = [], []
for i in x:
    if i < 0:
        s.append(abs(i))
    elif i == 0:
        k -= 1
    else:
        t.append(i)
s.append(0)
s.reverse()
t.insert(0, 0)
ans = 1145141919810
for i in range(k + 1):
    if len(s) - 1 >= i and len(t) - 1 >= k - i:
        c = 2 * min(s[i], t[k - i]) + max(s[i], t[k - i])
        if c < ans:
            ans = c
print(ans)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
l=tuple(map(int,input().split()))

ans=float("Inf")
for i in range(n-m+1):
  if l[i+m-1]<0:ret=abs(l[i])
  elif l[i]>0:ret=l[i+m-1]
  else:ret=2*min(abs(l[i+m-1]),abs(l[i]))+max(abs(l[i+m-1]),abs(l[i]))
  ans=min(ret,ans)
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
x=list(map(int,input().split()))
minus=[]
plus=[]
for i in range(N):
    if x[i]<0:
        minus.append(abs(x[i]))
    else:
        plus.append(x[i])
minus.append(0)
plus.append(0)

plus.sort()
minus.sort()


ans=int(1e9)
for i in range(K+1):
    if 0<=i<len(plus) and 0<=K-i<len(minus):
        ans=min(ans,plus[i]+minus[K-i]+min(plus[i],minus[K-i]))
print(ans)