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:
import sys
import math  # noqa
import bisect  # noqa
import queue  # noqa


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


def solve(X, K):
    N = len(X)

    cumsum = [0 for _ in range(N)]
    for i in range(1, N):
        cumsum[i] = abs(X[i] - X[i - 1]) + cumsum[i - 1]

    idx_zero = bisect.bisect_left(X, 0)

    ret = 1000000005
    for i in range(0, N):
        if X[i] >= 0:
            break
        res = -X[i]
        k = idx_zero - i
        if (k < K) and (idx_zero + K - k - 1 < N):
            res += cumsum[idx_zero + K - k - 1] - cumsum[i]
            ret = min(ret, res)

    return ret


if __name__ == '__main__':
    N, K = map(int, input().split())
    X = list(map(int, input().split()))

    res = 1000000005
    if min(X) >= 0:
        print(X[K - 1])
    elif max(X) <= 0:
        X = X[::-1]
        print(-X[K - 1])
    else:
        res = min(res, solve(X, K))
        X = [-x for x in X]
        res = min(res, solve(X[::-1], K))
        print(res)

Submission status: Accepted

Solution code:
# solution

nim, mike = map(int, input().split())
array = list(map(int, input().split()))
k = float("INF")
for i in range(nim-mike+1):
	l = array[i]
	r = array[i+mike-1]
	k = min(k, abs(l)+abs(r-l), abs(r)+abs(r-l))
print(k)

Submission status: Accepted

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
#from itertools import combinations # (string,3) 3回
#from collections import deque
#import collections.defaultdict(list)
#import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    n,k = readInts()
    X = readInts()
    m = float('inf')
    # 端だけ保存してあげればよい
    #left = []
    #right = []
    for i in range(n-k+1):
        l = X[i]
        r = X[k+i-1]
        m = min(m,min(abs(l),abs(r)) + r - l)
    print(m)
if __name__ == '__main__':
  main()

Submission status: Accepted

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

min = float('inf')
for i in range(N-K+1):
    left_cost = X[i]
    right_cost  = X[i+K-1]
    right_course = abs(right_cost)+abs(right_cost-left_cost)
    if min > right_course:
        min = right_course
    left_course = abs(left_cost)+abs(right_cost-left_cost)
    if min > left_course:
        min = left_course
        
print(min)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
ns = list(map(int, input().split()))
min_num = float('inf')
for i in range(n - k+1):
    l = ns[i]
    r = ns[i+k-1]
    min_num = min(min_num, abs(l) + abs(r-l), abs(r) + abs(l-r))
print(min_num)

Submission status: Accepted

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

ans = 114514191981036436433-4

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

Submission status: Accepted

Solution code:
def solve():
    N, K = map(int, input().split())
    X = list(map(int, input().split()))
    if 0 in X:
        N -= 1
        K -= 1
        if K == 0:
            return 0
        X.remove(0)
    ans = 10**9
    for i in range(N-K+1):
        if X[i+K-1]<=0:
            p = -X[i]
        elif X[i]>=0:
            p = X[i+K-1]
        else:
            p = X[i+K-1]-X[i]+min(X[i+K-1],abs(X[i]))
        ans = min(ans,p)
    return ans
print(solve())

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
x = list(map(int,input().split()))
mn = float("inf")
for i in range(n-k+1):
  if x[i] <= 0 and 0 <= x[i+k-1]:
    if x[i+k-1]-x[i] + min(abs(x[i+k-1]),abs(x[i])) < mn:
      mn = x[i+k-1]-x[i] + min(abs(x[i+k-1]),abs(x[i]))
  elif x[i+k-1] <= 0:
    if mn > -x[i]:
      mn = -x[i]
  else:
    if mn > x[i+k-1]:
      mn = x[i+k-1]
    break
print(mn)

Submission status: Accepted

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

    ans = float('inf')
    # 左から left 番目のろうそくから右へ連続した K 本のろうそくに火をつけるといい
    # 左端か右端か、近い方からつけ始める
    for left in range(N - K + 1):
        right = left + K - 1
        dist1, dist2 = min(abs(X[left]), abs(X[right])), abs(X[right] - X[left])
        ans = min(ans, dist1 + dist2)
    return ans

print(c_candles())

Submission status: Accepted

Solution code:
import sys

def main(lines):
  N, K = map(int, lines[0].split())
  a = list(map(int, lines[1].split()))
  ans = 1000000000000
  for i in range(N):
    if i + K - 1 >= N:
      break
    b = a[i]
    c = a[i + K - 1]
    if b < 0 and c >= 0:
      ans = min(ans, max(abs(b), abs(c)) + 2*min(abs(b), abs(c)))
    else:
      ans = min(ans, max(abs(b), abs(c)))
  print(ans)


if __name__ == '__main__':
    lines = []
    for l in sys.stdin:
        lines.append(l.rstrip('\r\n'))
    main(lines)

Submission status: Accepted

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

min_ = None
for i in range(n-k+1):
  res = min(abs(xs[i]) + abs(xs[i+k-1] - xs[i]), abs(xs[i+k-1]) + abs(xs[i] - xs[i+k-1]))
  if min_ is None:
    min_ = res
  else:
    min_ = min(res, min_)
print(min_)

Submission status: Accepted

Solution code:
N, K = map(int,input().split())
x = list(map(int,input().split()))
x.sort()
MIN = 10 ** 10
for i in range(N-K+1):
    if x[i+K-1] <= 0:
        MIN = min(MIN, -1 * x[i])
    elif 0 <= x[i]:
        MIN = min(MIN, x[i+K-1])
    else:
        MIN = min(MIN, -1 * x[i] + x[i+K-1] + min(-1 * x[i], x[i+K-1]))
print(MIN)

Submission status: Accepted

Solution code:
import sys

n, k, *x = map(int, sys.stdin.read().split())

def main():
    res = float('inf')
    for i in range(n - k + 1):
        j = i + k - 1
        if x[i] < 0:
            d = -x[i] if x[j] <= 0 else min(-x[i], x[j]) * 2 + max(-x[i], x[j])
        else:
            d = x[j]
        res = min(res, d)
    print(res)
    
if __name__ ==  '__main__':
    main()

Submission status: Accepted

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list
#from itertools import combinations # (string,3) 3回

mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    """
    n k
    x1, x2, ... xn

    5 3
    -30 -10 10 20 50
    K個は連続する区間で考えればよい。
    区間を決めると、原点から最初に負の方向に行くか、
    正の方向に行くかはすぐに決められる

    つまり
    k = 3なら
    [-30, -10, 10], [-10, 10, 20], [10, 20, 50]
    の３つに分けるっていうこと？
    """
    n,k = readInts()
    X = readInts()

    res = float('inf')
    for i in range(n-k+1):# n =5なら、 i:0 ~ 2まで回す [0:2],[1:3],[2,4]って感じ [3,6]は範囲外だからだめ
        left = X[i]
        right = X[i+k-1]
        #print(left,right,abs(left) + right - left,abs(right) + right - left)
        # abs(X[i] - X[i+k-1])で、端から端までの移動距離を求めて、
        # min(abs(X[i]), abs(X[i+k-1]))で、左、右どっちから始まるかを決める
        # どっちかまでいく移動距離 + 端から端までの移動距離 で最小値を求めることができる!!
        res = min(res, min(abs(left), abs(right)) + right - left)
    print(res)



if __name__ == '__main__':
  main()

Submission status: Accepted

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

zeroi = 0
while zeroi < N:
    if X[zeroi] >= 0:
        break
    zeroi += 1
if zeroi < N and X[zeroi] == 0:
    K -= 1
    N -= 1
    del X[zeroi]

xl = list(reversed(X[:zeroi]))
xr = list(X[zeroi:])

def solve():
    if K == 0:
        return 0
    minval = 2**60
    for i, x in enumerate(xl):
        r = K - (i+1)
        if r <= 0:
            d = -x
        elif r > len(xr):
            continue
        else:
            d = -x + 2 * xr[r-1]
        if minval > d:
            minval = d
    for i, x in enumerate(xr):
        l = K - (i+1)
        if l <= 0:
            d = x
        elif l > len(xl):
            continue
        else:
            d = x - 2 * xl[l-1]
        if minval > d:
            minval = d
    return minval

print(solve())

Submission status: Accepted

Solution code:
import math, sys
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from copy import deepcopy
from functools import lru_cache
from heapq import heapify, heappop, heappush
from itertools import accumulate, combinations, permutations
input = sys.stdin.readline
mod = 10**9 + 7
ns = lambda: input().strip()
ni = lambda: int(input().strip())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))

n, k = nm()
x = nl()

if 0 in x:
    k -= 1
if n == 1:
    print(x[0])
    exit()

zero = bisect_left(x, 0)
costs = []
#print(zero, max(zero - k, 0), min(zero + k, n - k) + 1)
for i in range(max(zero - k, 0), min(zero + k, n - k) + 1):
    if x[i] < 0 and x[i+k-1] > 0:
        costs.append(-2 * x[i] + x[i+k-1])
        costs.append(-1 * x[i] + 2 * x[i+k-1])
    else:
        costs.append(max(abs(x[i]), abs(x[i+k-1])))
    #print(i, x[i], costs)
print(min(costs))

Submission status: Accepted

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

distance = [0]
for i in range(1, n):
  distance.append(candle[i] - candle[i-1] + distance[i-1])

ans = float('inf')
for i in range(n-k+1):
  res = distance[i+k-1] - distance[i]
  if candle[i+k-1] < 0:
    res += abs(candle[i+k-1])
  elif candle[i] >= 0:
    res += candle[i]
  else:
    res += min(candle[i+k-1], abs(candle[i]))
  ans = min(ans, res)
print(ans)

Submission status: Accepted

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

mi = sys.maxsize

for i in range(n-k+1):
    l = x[i]
    r = x[i+k-1]
    #print(l,r)
    vall = abs(l) + abs(r - l)
    valr = abs(r) + abs(r - l)
    mi = min(mi,min(vall,valr))

print(mi)

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 = min(abs(x[i + K - 1]), abs(x[i])) + abs(x[i + K - 1] - x[i])
    m = min(temp, m)
print(m)

Submission status: Accepted

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

ans=np.inf
for L in range(0,N-K+1):
  R=L+K-1
  ans=min(ans, X[R]-X[L]+min(abs(X[R]),abs(X[L])))
  #print(R,L)
  
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
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 INT(): return int(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()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, K = MAP()
X = LIST()

# dist = 0
s = []
l = []
s = deque(s)
l = deque(l)
for x in X:
    if x < 0:
        s.appendleft(-1 * x)
    else:
        l.append(x)
# s.sort()
# print(s, l)

left = 0
right = 0
q = []
ans = INF
for i in range(N-K+1):
    left = i
    right = i + K - 1
    ans = min(ans, min(abs(X[left]), abs(X[right])) + X[right] - X[left])
print(ans)

Submission status: Accepted

Solution code:
n,k,*a=map(int,open(0).read().split())
print(min(r-l+min(abs(r),abs(l))for l,r in zip(a,a[k-1:])))

Submission status: Accepted

Solution code:
n,k,*a=map(int,open(0).read().split());print(min(r-l+min(abs(r),abs(l))for l,r in zip(a,a[k-1:])))

Submission status: Accepted

Solution code:
n,k,*x=map(int,open(0).read().split())
if x[0]>=0:
  ans=x[k-1]
elif x[-1]<=0:
  ans=abs(x[~(k-1)])
else:
  ans=10**10
  for i in range(n-k+1):
    l=x[i]
    r=x[i+k-1]
    if l<=0<=r:
      ll=abs(l)
      rr=abs(r)
      tmp=min(ll+2*rr,2*ll+rr)
      ans=min(ans,tmp)
      
print(ans)

Submission status: Accepted

Solution code:
n,k,*x=map(int,open(0).read().split())

if x[0]>=0:
  ans=x[k-1]
elif x[-1]<=0:
  ans=abs(x[~(k-1)])

elif n==k:
  l=abs(x[0])
  r=abs(x[-1])
  ans=min(l+l+r,r+r+l)
else:
  ans=10**10
  for i in range(n-k+1):
    l=x[i]
    r=x[i+k-1]
    if l<=0<=r:
      ll=abs(l)
      rr=abs(r)
      tmp=min(ll+2*rr,2*ll+rr)
      ans=min(ans,tmp)
      
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
time = 3 * 10 ** 8

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

print(time)

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

Submission status: Accepted

Solution code:
import sys

def solve():
    input = sys.stdin.readline
    N, K = map(int, input().split())
    X = [int(x) for x in input().split()]
    left = [0]
    right = [0]
    for x in X:
        if x < 0: left.append(-x)
        else: right.append(x)
    left.sort()
    lenl = len(left)
    lenr = len(right)
    Ans = 100000000000000
    for l in range(min(lenl, K + 1)):
        r = K - l
        if r < lenr:
            Ans = min(min(left[l], right[r]) + left[l] + right[r], Ans)
    #print(left, right)
    print(Ans)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import bisect
N, K = map(int,input().split())
x = list(map(int,input().split()))
ans = float("inf")
if x[0]*x[-1] >= 0:
    if x[0] >= 0:
        ans = x[K-1]
    else:
        ans = -x[-K]
    print(ans)
else:
    M = []
    P = []
    for e in x:
        if e > 0:
            P.append(e)
        else:
            M.append(-e)
    M.sort()
    M = [0] + M
    P = [0] + P
    for k in range(max(len(P),len(M))):
        if k < len(P) and 0 <= K-k < len(M):
#            print(M[K-k],P[k])
            ans = min(ans,2*M[K-k]+P[k],M[K-k]+2*P[k])
    print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
X = list(map(int,input().split()))
ls = []
rs = []
for x in X:
    if x < 0:
        ls.append(-x)
    else:
        rs.append(x)
ls.reverse()

ans = float('inf')
if len(ls) >= K:
    ans = min(ans, ls[K-1])
if len(rs) >= K:
    ans = min(ans, rs[K-1])

for l in range(1,K):
    if l > len(ls): break
    r = K-l
    if r > len(rs): continue
    ans = min(ans, ls[l-1]*2 + rs[r-1])
    ans = min(ans, rs[r-1]*2 + ls[l-1])
print(ans)

Submission status: Accepted

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

import bisect

idx_r = bisect.bisect_left(x, 0)

if idx_r < N and x[idx_r] == 0:
    idx_l = idx_r
else:
    idx_l = idx_r - 1

ans = 1000000007
    
# right
if 0 <= idx_r + K - 1 < N:
    ans_tmp = x[idx_r + K - 1]
    ans = min(ans, ans_tmp)

# left
if 0 <= idx_l - K + 1 < N:
    ans_tmp = -x[idx_l - K + 1]
    ans = min(ans, ans_tmp)

# right -> left
for i in range(N):
    if 0 <= idx_r - K + 1 + i < idx_r + i < N:
        ans_tmp = 2 * x[idx_r + i] - x[idx_r - K + 1 + i]
        ans = min(ans, ans_tmp)

# left -> right
for i in range(N):
    if 0 <= idx_l - i < idx_l + K - 1 - i < N:
        ans_tmp = x[idx_l + K - 1 - i] - 2 * x[idx_l - i]
        ans = min(ans, ans_tmp)

print(ans)

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):
	ans=min(ans,abs(L[i])+abs(L[i+K-1]-L[i]),abs(L[i+K-1])+abs(L[i+K-1]-L[i]))
print(ans)

Submission status: Accepted

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

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

if k == 1:
    min_num = 10**20
    for i in x:
        if abs(i) < min_num:
            min_num = abs(i)
    print(min_num)
    exit()

min_dist = 10**20

dist = 0

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

print(min_dist)

Submission status: Accepted

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

res = 1e+9
for i in range(N-K+1):
    if abs(x[i]) <= abs(x[i+K-1]):
        res = min(res,abs(x[i]) + abs(x[i+K-1] - x[i]))
    else:
        res = min(res,abs(x[i+K-1]) + abs(x[i+K-1] - x[i]))
print(res)

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 x[i] * x[i+K-1] < 0:
        ans = min(ans, abs(x[i+K-1]) + abs(x[i]) + min(abs(x[i+K-1]), abs(x[i])))
    elif x[i] >= 0:
        ans = min(ans, x[i+K-1])
    else:
        ans = min(ans, abs(x[i]))

print(ans)

Submission status: Accepted

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

P=[]
N=[]
Z=0
for x in X:
    if x < 0: N.append(-x)
    elif x > 0: P.append(x)
    else: Z+=1

P.sort()
N.sort()
Pc=len(P)
Nc=len(N)

L=[]
for x in N:
    L.append(x)
R=[]
for x in P:
    R.append(x)

if Z>=K:
    print(0)
    exit()
K-=Z
ans=10**9
count=0
for x in P:
    count+=1
    if count==K:
        ans = min(ans, x)
        break
    if Nc+count>=K:
        ans = min(ans, 2*x+L[K-count-1])
count=0
for x in N:
    count+=1
    if count==K:
        ans = min(ans, x)
        break
    if Pc+count>=K:
        ans = min(ans, 2*x+R[K-count-1])
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
a = list(map(int, input().split()))
z = -1
res = float("inf")
for r in range(N):
  if a[r] < 0:
    z = r
    continue
  if r < K - 1: continue
  x = r - z
  y = a[z - (K - x) + 1]
  if K == x: y = 0
  t = min(abs(a[r]), abs(y))
  if r - z >= K: t = 0
  res = min(res, abs(a[r]) + abs(y) + t)
for l in range(N):
  if z - l + 1 == K:
    res = min(res, abs(a[l]))
    break
print(res)

Submission status: Accepted

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

neg = []
pos = []
for i in range(n):
    if X[i] < 0:
        neg.append(X[i])
    else:
        pos.append(X[i])

ans = 10**18
neg.sort(reverse=True)
pos.sort()
for a in range(len(neg)+1):
    b = k - a
    if b < 0 or b > len(pos):
        continue
    else:
        if a == 0:
            ans = min(ans, pos[b-1])
        elif b == 0:
            ans = min(ans, abs(neg[a-1]))
        else:
            ans = min(ans, min(2*abs(neg[a-1])+pos[b-1], 2*pos[b-1]+abs(neg[a-1])))
print(ans)

Submission status: Accepted

Solution code:
def main():
    n, k = map(int, input().split())
    x = [int(x) for x in input().split()]
    answer = float("inf")
    if 1 < n:
        for i in range(n - k + 1):
            if x[i + k - 1] < 0:
                answer = min(answer, -x[i])
            elif 0 < x[i]:
                answer = min(answer, x[i + k - 1])
            else:
                answer = min(answer, min(abs(x[i]), abs(x[i + k - 1])) + x[i + k - 1] - x[i])
    else:
        answer = abs(x[0])
    print(answer)


if __name__ == '__main__':
    main()

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

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, K = MAP()
x = LIST()

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

Submission status: Accepted

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

time = 100000000000007
for i in range(0, N-K+1):
  if X[i] < 0 and X[i+K-1] > 0:
    if abs(X[i]) >= abs(X[i+K-1]):
      time = min(abs(X[i+K-1]-X[i]) + abs(X[i+K-1]),time)
    else:
      time = min(abs(X[i+K-1]-X[i]) + abs(X[i]),time)
  if X[i] >= 0:
      time = min(abs(X[i+K-1]-X[i]) + abs(X[i]),time)
  if X[i+K-1] <= 0:
      time = min(abs(X[i+K-1]-X[i]) + abs(X[i+K-1]),time)

print(time)

Submission status: Accepted

Solution code:
N, K = list(map(int, input().split()))
x = list(map(int, input().split()))
ans = min([abs(x[0]) + abs(x[0] - x[K-1]), abs(x[K-1]) + abs(x[0] - x[K-1])])

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

Submission status: Accepted

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

pos = []
neg = []
for i in lst:
    if i>=0:
        pos.append(i)
    else:
        neg.append(-i)
neg.sort()
pos = pos + [float("INF")]*max(k-len(pos),0)
neg = neg + [float("INF")]*max(k-len(neg),0)
# print(pos)
# print(neg)

ans = min(pos[k-1],neg[k-1])
for i in range(1,k):
    ans = min(ans, pos[i-1]*2+neg[k-i-1])
for i in range(1,k):
    ans = min(ans, neg[i-1]*2+pos[k-i-1])

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
def main():
    N, K = map(int, input().split())
    x = list(map(int, input().split()))
    neg_dists = []
    pos_dists = []
    exists_zero = False
    for xi in x:
        if xi < 0:
            neg_dists.append(abs(xi))
        elif xi > 0:
            pos_dists.append(abs(xi))
        else:
            exists_zero = True
    neg_dists.sort()
    pos_dists.sort()
    ans = 10 ** 9
    count = K - int(exists_zero)
    for i in range(count):
        d = 0
        if i >= len(neg_dists):continue
        d += neg_dists[i]
        if len(pos_dists) == 0 or count-2-i >= len(pos_dists):continue
        d += pos_dists[count-2-i] + neg_dists[i]
        ans = min(ans, d)
    for i in range(count):
        d = 0
        if i >= len(pos_dists):continue
        d += pos_dists[i]
        if len(neg_dists) == 0 or count-2-i >= len(neg_dists):continue
        d += neg_dists[count-2-i] + pos_dists[i]
        ans = min(ans, d)
    if len(neg_dists) > 0 and count <= len(neg_dists):ans = min(ans, neg_dists[count-1])
    if len(pos_dists) > 0 and count <= len(pos_dists):ans = min(ans, pos_dists[count-1])
    if exists_zero and len(neg_dists) == 0 and len(pos_dists) == 0:ans = 0
    print(ans)
            
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin
inf = 1 << 60
mod = 1000000007

ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

n, k = na()
x = na()

def dist(l, r):
    mn = min(abs(l), abs(r))
    mx = max(abs(l), abs(r))
    if l < 0 and r < 0:
        return mx
    elif l >= 0 and r >= 0:
        return mx
    else:
        return mn * 2 + mx

ans = inf
for i in range(n - k + 1):
    ans = min(ans, dist(x[i], x[i + k - 1]))

print(ans)

Submission status: Accepted

Solution code:

def main():
    n,k = map(int,input().split())
    x_s = list(map(int,input().split()))
    left = []
    right = []
    for x in x_s:
        if x < 0:
            left.append(abs(x))
        else:
            right.append(abs(x))

    left = sorted(left)
    right = sorted(right)
    mn = 100000000000
    for i in range(0,k+1):
        #print(i,k-i)
        if i > len(left) or k-i > len(right):
            #print("index_error!")
            continue

        l = left[i-1] if i > 0 else 0
        r = right[k-i-1] if k-i > 0 else 0
        first_move = min(l,r)
        mn = min(mn,l+r+first_move)
        #print("l:",l,"r:",r,"mn:",mn)
    print(mn)








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

Submission status: Accepted

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

  elif (x[k+i-1] <= 0):
    temp = -x[i]
    
  if temp < ans:
    ans = temp
    
print(ans)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10 ** 7)

i_i = lambda: int(i_s())
i_l = lambda: list(map(int, stdin.readline().split()))
i_s = lambda: stdin.readline().rstrip()

N, K = i_l()
x = i_l()

ans = 1 << 31
for i in range(N-K+1):
    if x[i] >= 0:
        ans = min(ans, x[i+K-1])
    elif x[i+K-1] <= 0:
        ans = min(ans, abs(x[i]))
    elif x[i] <= 0 and 0 <= x[i+K-1]:
        ans = min(ans, x[i+K-1] - x[i] + min(abs(x[i+K-1]), abs(x[i])))

print(ans)

Submission status: Accepted

Solution code:
def 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])+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 = list(map(int, input().split()))

    cost = float("inf")

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

    print(cost)


if __name__ == "__main__":
    solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
X = list(map(int, input().split()))
XR = [x if x > 0 else x * 2 for x in X]
XL = [x * 2 if x > 0 else x for x in X]

ans = 10**9
for i in range(k-1, n):
  dist_R = XR[i] - min(0, XR[i-k+1])
  dist_L = max(0, XL[i]) - XL[i-k+1]
  #print(i, dist_R, dist_L)
  ans = min(ans, dist_R, dist_L)
print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
x=list(map(int,input().split()))
plusdis=[]
minusdis=[]
l=[]
for i in range(N):
    if x[i]<0:
        minusdis.append(abs(x[i]))
    else:
        plusdis.append(x[i])
minusdis.sort()
#print(minusdis,plusdis)
minum=0
plnum=0
mindist=float("inf")
for i in range(K+1):
    minum=i
    plnum=K-i
    #print(minum,plnum)
    if (minum<=len(minusdis))and(plnum<=len(plusdis)):
        if minum==0:
            mindist=min(plusdis[plnum-1],mindist)
        elif plnum==0:
            mindist = min(minusdis[minum - 1], mindist)
        else:
            mindist = min(plusdis[plnum - 1]+minusdis[minum - 1]+min(plusdis[plnum-1],minusdis[minum - 1]), mindist)
        #print(mindist)
    #input()
print(mindist)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
X = [int(x) for x in input().split()]
Xp = sorted([x for x in X if x >= 0])
Xm = sorted([x for x in X if x < 0 ])[::-1]
if not Xp: #Xpが空
  print(-Xm[k-1])
elif not Xm: #Xmが空
  print(Xp[k-1])
else:
  res = 10**10
  for m in range(k - min(k, len(Xp)), min(k, len(Xm)) + 1):
    p = k - m
    if m == 0:
      res = min(res, Xp[k-1])
    elif p == 0:
      res = min(res, -Xm[k-1])
    else:
      res = min(res, 2*Xp[p-1]-Xm[m-1], -2*Xm[m-1]+Xp[p-1])
  print(res)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
lis = list(map(int, input().split()))

res = 10**9
for i in range(n - m + 1):
    res = min(res, lis[i + m - 1] - lis[i] + min(abs(lis[i]), abs(lis[i + m - 1])))
print(res)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
lis = list(map(int, input().split()))
su = []

for i in range(n):
    su.append(lis[i] - lis[0])

res = 10**9
for i in range(n - m + 1):
    res = min(res, su[i + m - 1] - su[i] + min(abs(lis[i]), abs(lis[i + m - 1])))
print(res)