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:
###############################################################################

from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy


mod = 1


def intin():
    input_tuple = input().split()
    if len(input_tuple) <= 1:
        return int(input_tuple[0])
    return tuple(map(int, input_tuple))


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


def intinl(count):
    return [intin() for _ in range(count)]


def modadd(x, y):
    global mod
    return (x + y) % mod


def modmlt(x, y):
    global mod
    return (x * y) % mod


def lcm(x, y):
    while y != 0:
        z = x % y
        x = y
        y = z
    return x


def combination(x, y):
    assert(x >= y)

    if y > x // 2:
        y = x - y

    ret = 1

    for i in range(0, y):
        j = x - i
        i = i + 1

        ret = ret * j
        ret = ret // i

    return ret


def get_divisors(x):
    retlist = []
    for i in range(1, int(x**0.5) + 3):
        if x % i == 0:
            retlist.append(i)
            retlist.append(x // i)
    return retlist


def get_factors(x):
    retlist = []
    for i in range(2, int(x**0.5) + 3):
        while x % i == 0:
            retlist.append(i)
            x = x // i
    retlist.append(x)
    return retlist


def make_linklist(xylist):
    linklist = {}
    for a, b in xylist:
        linklist.setdefault(a, [])
        linklist.setdefault(b, [])
        linklist[a].append(b)
        linklist[b].append(a)
    return linklist


def calc_longest_distance(linklist, v=1):
    distance_list = {}
    distance_count = 0
    distance = 0
    vlist_previous = []
    vlist = [v]
    nodecount = len(linklist)

    while distance_count < nodecount:
        vlist_next = []
        for v in vlist:
            distance_list[v] = distance
            distance_count += 1
            vlist_next.extend(linklist[v])
        distance += 1
        vlist_to_del = vlist_previous
        vlist_previous = vlist
        vlist = list(set(vlist_next) - set(vlist_to_del))

    max_distance = -1
    max_v = None
    for v, distance in distance_list.items():
        if distance > max_distance:
            max_distance = distance
            max_v = v

    return (max_distance, max_v)


def calc_tree_diameter(linklist, v=1):
    _, u = calc_longest_distance(linklist, v)
    distance, _ = calc_longest_distance(linklist, u)
    return distance


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


def calc_cost(plist, left, right):
    if left == right:
        return abs(plist[left])

    if plist[left] >= 0:
        return plist[right]

    if  plist[right] <= 0:
        return abs(plist[left])

    left_cost = abs(plist[left])
    right_cost = plist[right]
    return min(left_cost, right_cost) * 2 + max(left_cost, right_cost)


def main():
    n, k = intin()
    xlist = intina()

    min_cost = float('inf')
    for i in range(n - k + 1):
        min_cost = min(calc_cost(xlist, i, i + k - 1), min_cost)
    print(min_cost)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
def f(x,y):
    if y>0:return x
    elif x<0:return -y
    elif x > -y:return x-2*y
    else: return 2*x-y
a,b=map(int,input().split())
c=list(map(int,input().split()))
d=f(c[-1],c[-b])
for i in range(a-b):
    if d > f(c[i+b-1],c[i]):
        d=f(c[i+b-1],c[i])
print(d)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
xs = list(map(int, input().split()))
cand = []
for l, r in zip(xs, xs[k-1:]):
  ds = sorted([abs(l), abs(r)])
  if(l * r > 0):
    cand.append(ds[1])
  else:
    cand.append(ds[0] * 2 + ds[1])
print(min(cand))

Submission status: Accepted

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

min_t = 10e9
for i in range(N - K + 1):
    e = i + K - 1
    l = min(x[i], 0)
    r = max(x[e], 0)

    t = min(-l, r) * 2 + max(-l, r)
    min_t = min(min_t, t)

print(min_t)

Submission status: Accepted

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

min_t = 10e9
for s in range(n - k + 1):
    e = s + k - 1
    l = min(x[s], 0)
    r = max(x[e], 0)

    t = min(-l, r) * 2 + max(-l, r)
    min_t = min(min_t, t)

print(min_t)

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

Submission status: Accepted

Solution code:
from bisect import bisect_left
N,K=[int(a) for a in input().split(" ")]
X=[int(a) for a in input().split(" ")]
i = bisect_left(X,0)
if 0 in X:
    K=K-1
else:
    X.insert(i, 0)
ans = 10**10
for left in range(max(i-K, 0), i+1):
    right = left+K
    if right>=len(X):
        break
    lw, rw = -X[left], X[right]
    ans = min(ans, lw+rw+min(lw,rw))
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):
    res = min(
        abs(x[i]) + abs(x[i + K - 1] - x[i]),
        abs(x[i + K - 1]) + abs(x[i] - x[i + K - 1]),
    )
    ans = min(res, ans)
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
x_list=list(map(int,input().split()))
countp=0
countz=0
countn=0
for i in x_list:
    if i>0:
        countp=countp+1
    elif i==0:
        countz=countz+1
    else:
        countn=countn+1
if countz==0:
    if countp>=countn:
        if countn+k-1<=n-1:
            Min=x_list[countn+k-1]
        else:
            Min=10**16
        for i in range(countn):
            if countn+k-1-i-1<=n-1:
                m=min(x_list[countn+k-1-i-1]-2*x_list[countn-i-1],2*x_list[countn+k-1-i-1]-x_list[countn-i-1])
                Min=min(Min,m)
    else:
        if countn-1-k+1>=0:
            Min=-x_list[countn-1-k+1]
        else:
            Min=10**16
        for i in range(countp):
            if countn+i-k+1>=0:
                m=min(x_list[countn+i]-2*x_list[countn+i-k+1],2*x_list[countn+i]-x_list[countn+i-k+1])
                Min=min(Min,m)
else:
    if countp>=countn:
        if countn+k-1<=n-1:
            Min=x_list[countn+k-1]
        else:
            Min=10**16
        for i in range(countn):
            if countn+k-1-i-1<=n-1:
                m=min(x_list[countn+k-1-i-1]-2*x_list[countn-i-1],2*x_list[countn+k-1-i-1]-x_list[countn-i-1])
                Min=min(Min,m)
    else:
        if countn-k>=0:
            Min=-x_list[countn-k+1]
        else:
            Min=10**16
        for i in range(countp):
            if countn+i-k+1>=0:
                m=min(x_list[countn+i]-2*x_list[countn+i-k+1],2*x_list[countn+i]-x_list[countn+i-k+1])
                Min=min(Min,m)
print(Min)

Submission status: Accepted

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

N, K = map(int, input().split())
L = [int(v) for v in input().split()]
NL = [0] * (N - K + 1)

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

Submission status: Accepted

Solution code:
# -*- coding:utf-8 -*-

"""解説
https://www.youtube.com/watch?v=5O4k1n5Ejzw

区間を考える問題

-30 -10 0 10 20 50

・K = 3のとき、

0座標を必ず含める、ある連続するK個のロウソクについて考える

・-30 -10 0 10
・-10 0 10 20
・0 10 20 50

左端と右端に到達する最小値を求めていけばよくて、間のロウソクは無視してよい（必ず移動中に火をつけるので）

すべての場合について求めて、その中の最小値が答え
"""
def solve():
    N, K = list(map(int, input().split()))
    X = list(map(int, input().split()))
    if 0 in X:
        # 0座標にロウソクがあるなら、火をつけるロウソクをひとつ減らしてよい
        K -= 1
    else:
        X.append(0)
    X.sort()

    origin_i = X.index(0)
    left_i = max(origin_i-K, 0)

    INF = 10**12
    ans = INF
    while left_i <= origin_i:
        if left_i+K < len(X):
            tmp1 = abs(X[left_i]-0)*2 + abs(X[left_i+K]-0)
            tmp2 = abs(X[left_i]-0) + abs(X[left_i+K]-0)*2
        else:
            break
        ans = min(ans, tmp1, tmp2)
        left_i += 1
    print(ans)

if __name__ == "__main__":
    solve()

Submission status: Accepted

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

distance = float('inf')
for i in range(N-K+1):
    tmp_distance = abs(X[i]) + abs(X[i+K-1]-X[i])
    distance = min(distance, tmp_distance)
    tmp_distance = abs(X[i+K-1]) + abs(X[i+K-1]-X[i])
    distance = min(distance, tmp_distance)
print(distance)

Submission status: Accepted

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

MIN_SUM = float('inf')
for i in range(N-K+1):
  MIN_SUM = min(MIN_SUM,X[i+K-1]-X[i]+abs(X[i]),X[i+K-1]-X[i]+abs(X[i+K-1]))
print(MIN_SUM)

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

Submission status: Accepted

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

print(min(r - l + min(abs(l), abs(r)) for l, r in zip(X, X[K - 1:])))

Submission status: Accepted

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

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

Submission status: Accepted

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

minv = 10**9

for i in range(n-k+1):
    head = lista[i]
    tail = lista[i+k-1]
    if head*tail <0:
        if abs(head)>abs(tail):
            temp = abs(head) + 2*abs(tail)
        else:
            temp = 2*abs(head) + abs(tail)
        if minv>temp:
            minv=temp
    else:
        temp = max(abs(head),abs(tail))
        if minv>temp:
            minv=temp
            
print(minv)

Submission status: Accepted

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

Submission status: Accepted

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

if 0 in x:
    K -= 1

cand = []
hasleft = x[0] < 0
hasright = x[N-1] > 0
if K == 0:
    cand = [0]
else:
    for i in range(N-K+1):
        left = x[i]
        right = x[i+K-1]
        if left < 0 and right > 0:
            cand.append(min(abs(left)*2+right, right*2+abs(left)))
        elif right < 0:
            cand.append(abs(left))
        elif left > 0:
            cand.append(right)
print(min(cand))

Submission status: Accepted

Solution code:
import numpy as np
from copy import deepcopy

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

X_plus = [x for x in X if x > 0]
X_minus = list(reversed([abs(x) for x in X if x < 0]))

X_plus.append(int(1e10)) # 無限大を加えておく
X_minus.append(int(1e10))

if 0 in X: # ろうそくが0にある時の処理
  K -= 1

if K == 0:
  ans = 0
elif K == 1:
  ans = min(X_plus[0], X_minus[0])
else:
  ans = int(1e10) # 初期値
  if len(X_plus) >= K: # 正方向に一直線で進む場合
    var_straight_plus = X_plus[K-1]
    ans = min(ans, var_straight_plus)
  if len(X_minus) >= K: # 負方向に一直線で進む場合
    var_straight_minus = X_minus[K-1]
    ans = min(ans, var_straight_minus)
  # 一度折り返してから正方向に進む場合
  lst_return_plus = [] 
  for s in range(max(1, K-len(X_plus)), min(len(X_minus), K-1)+1):
    var = 2 * X_minus[s-1] + X_plus[K-s-1]
    lst_return_plus.append(var)
  var_return_plus = min(lst_return_plus)
  ans = min(ans, var_return_plus)
  # 一度折り返してから負方向に進む場合
  lst_return_minus = [] 
  for s in range(max(1, K-len(X_minus)), min(len(X_plus), K-1)+1):
    var = 2 * X_plus[s-1] + X_minus[K-s-1]
    lst_return_minus.append(var)
  var_return_minus = min(lst_return_minus)
  ans = min(ans, var_return_minus)
  

print(ans)

Submission status: Accepted

Solution code:
import sys

def ans(index, array, k):
    r = right(index, array, k)
    l =  left(index, array, k)
    return min(r, l)


def right(index, array, k):
    start = max(index, k-1)
    count = sys.maxsize
    for i in range(start, min(len(array), k+index)):
        tmp = array[i]
        j = index - (k - (i - index + 1))
        tmp += array[i] - array[j]
        count = count if count < tmp else tmp

    if len(array) > (index + k - 1):
        count = count if count < array[index + k - 1] else array[index + k - 1]
    
    return count

def left(index, array, k):
    n = len(array)
    start = min(index, n - k + 1)
    count = sys.maxsize
    
    for i in range(max(0, start - k), start):
        tmp = -array[i]
        j = k + i - 1
        tmp += -array[i] + array[j]
        count = count if count < tmp else tmp

    if index >= k:
        count = count if count < -array[index-k] else -array[index-k]
    
    return count

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

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

index = n
for i in range(n):
    if x[i] >= 0:
        index = i
        break

print(ans(index, x, k))

Submission status: Accepted

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

ans = 10**9
for i in range (N-K+1):
    front = np.array(x[i])
    end   = np.array(x[i+K-1])
    
    if np.sign(front)!= np.sign(end):
        ans_temp = min (abs(front)*2+abs(end),abs(front)+abs(end)*2)
    else:
        ans_temp = max(abs(front),abs(end))
    
    if ans_temp <= ans:
        ans = ans_temp
print(ans)

Submission status: Accepted

Solution code:
from bisect import *

n, k = map(int, input().split())
candles = list(map(int, input().split()))
i0 = bisect_right(candles, 0)
MIN = float("inf")
if i0 - k >= 0:
    MIN = -candles[i0 - k]
i_start = max(0, i0 - k + 1)
if 0 in candles:
    i0 -= 1
if i0 + k - 1 <= n - 1:
    MIN = min(MIN, candles[i0 + k - 1])
i_end = min(i0, n - k + 1)
for i in range(i_start, i_end):
    L=-candles[i]
    R=candles[i+k-1]
    temp=L+R+min(L,R)
    if temp<MIN:
        MIN=temp
print(MIN)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
N, K = map(int, input().split())
x = list(map(int, input().split()))

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

Submission status: Accepted

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

ans = (x[-1] - x[0]) ** 2
for i in range(n - k + 1):
    xl = x[i]
    xr = x[i + k - 1]

    a = min(abs(xl) + abs(xr - xl), abs(xr) + abs(xl - xr))
    if a < ans:
        ans = a

print(ans)

Submission status: Accepted

Solution code:
N,K = map(int, input().strip().split(' '))
x = list(map(int, input().strip().split(' ')))
min_cost = float('inf')
if N > 2*K:
  for i,d in enumerate(x):
    if d >= 0:
      break
  x = x[i-K:i+K]
for i in range(len(x)-K+1):
  n_cost = -min(x[i], 0)
  p_cost = max(0, x[i+K-1])
  cost = n_cost + p_cost + min(n_cost, p_cost)
  if min_cost > cost:
    min_cost = cost
print(min_cost)

Submission status: Accepted

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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


ans = float("inf")
for i in range(n-k+1):
  #tmpの左端と右端の符号が同じなら、端から移動していく
  if (a[i] <= 0 and a[i+k-1] <= 0) or (a[i] >= 0 and a[i+k-1] >= 0):
    cost = max(abs(a[i]), abs(a[i+k-1]))
  #選んだろうそくが正負にまたがる場合、左端と右端の近いほうに移動してから  
  else:
    cost = min(abs(a[i]), abs(a[i+k-1]))*2 + max(abs(a[i]), abs(a[i+k-1]))
    
  if ans > cost:
    ans = cost
    
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from math import *
from itertools import *
from collections import *
from functools import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, K: int, x: "List[int]"):
    ret = float('inf')
    for l, r in zip(x, x[K-1:]):
        ret = min(ret, abs(r - l) + min(abs(l), abs(r)))
    return ret


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    x = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    result = solve(N, K, x)
    print(result)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

o = []

for i in range(N-K+1):
    l = x[i]
    r = x[i+K-1]
    if r < 0:
        o.append(-l)
    elif 0 < l:
        o.append(r)
    else:
        o.append(min(-l,r)*2+max(-l,r))

print(min(o))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import copy
import collections
from bisect import bisect_left
from bisect import bisect_right
	
def main():
	N, K = map(int, input().split())
	X = input().split(" ")
	X = [int(s) for s in X]
	
	left_val = bisect_left(X, 0)
	start = 0
	if left_val - K >= 0:
		start = left_val - K
		
	ans = -1
	while True:
		end = start + (K-1)
		#print(end)
		if end >= len(X):
			break
		
		tmp = X[end] - X[start]
		tmp2 = min(abs(X[start] - 0), abs(X[end] - 0))
		
		if ans == -1 or ans > tmp + tmp2:
			ans = tmp + tmp2
			
		start += 1
		
	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**10
for i in range(N):
    if i+K-1 >= N:
        break
    s1 = abs(x[i]) + abs(x[i]-x[i+K-1])
    s2 = abs(x[i+K-1]) + abs(x[i]-x[i+K-1])
    ans = min(ans, s1, s2)
print(ans)

Submission status: Accepted

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

xp = []
xn = []
for i in x:
    if i >= 0:
        xp += [i]
    else:
        xn += [abs(i)]
    
xn.sort()
pl = len(xp)
pn = len(xn)

ans = 2 ** 30

for i in range(pl):
    if K-2-i < pn:
        if K-2-i >= 0:
            tmp = xp[i] * 2 + xn[K-2-i]
        elif i == K-1:
            tmp = xp[i] 
    else:
        continue
    ans = min(ans,tmp)


for i in range(pn):
    if K-2-i < pl:        
        if K-2-i >= 0:
            tmp = xn[i] * 2 + xp[K-2-i]
        elif i == K-1:
            tmp = xn[i]
    else:
        continue
    ans = min(ans,tmp)

print(ans)

Submission status: Accepted

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

infty = 10**9
c = bisect.bisect_left(x,0)
if c == N:
    print(-x[-K])
    exit()
elif x[c] > 0:
    K += 1
    N += 1
    x.insert(c,0)

if c >= K-1:
    turn = c-(K-1)
else:
    turn = 0

ans = infty
while turn <= c and turn + K <= N:
    L = -x[turn]
    R = x[turn + K - 1]
    cur = L + R + min(L,R)
    if cur < ans:
        ans = cur
    turn += 1

print(ans)

Submission status: Accepted

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


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

    distance.append(dist)

print(min(distance))

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

Submission status: Accepted

Solution code:
import math
def abssum(nums):
    nums_length = len(nums)
    result = 0
    for i in range(nums_length-1):
        result += abs(nums[i]-nums[i+1])
    return result



N,M = input().split(" ")
N = int(N)
M = int(M)
temp = list(map(int,input().split(" ")))
diffs = [abs(n1-n2) for n1,n2 in zip(temp[0:-1],temp[1:])]
fromzero = [abs(0-n) for n in temp]

scores = [sum(diffs[0:M-1])]

for i in range(1,N-M+1):
    scores.append(scores[i-1]-diffs[i-1]+diffs[i+M-2])

for i,(cand1,cand2) in enumerate(zip(fromzero[0:N-M+1],fromzero[M-1:])):
    scores[i] += min(cand1,cand2)
print(min(scores))

Submission status: Accepted

Solution code:
from sys import stdin
N, K = [int(_) for _ in stdin.readline().rstrip().split()]
X = [int(_) for _ in stdin.readline().rstrip().split()]
result = []
for l, r in zip(X,X[K-1:]):
    result.append(r - l + min(abs(l), abs(r)))
print(min(result))

Submission status: Accepted

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

res = []

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

print(min(res))

Submission status: Accepted

Solution code:


def main():
    num, walk_num = map(int, input().split())
    data_kari = list(map(int, input().split()))
    data = [0 for i in range(num)]

    for i in range(num):
        if data_kari[i] >= 0:
            break
    if data_kari[i] < 0:
        i += 1

    for j in range(i):
        if j == i - 1:
            data[j] = data_kari[j]
        else:
            data[j] = data_kari[j] - data_kari[j + 1]

    if i == num:
        i -= 1
    data[i] = data_kari[i]
    for j in range(i + 1, num):
        data[j] = data_kari[j] - data_kari[j -1]

    start_ind = max(0,i - walk_num + 1)

    data_sum_fu = 0
    data_sum_sei = 0

    for i in range(start_ind, start_ind + walk_num):
        if data[i] > 0:
            data_sum_sei += data[i]
        else:
            data_sum_fu += abs(data[i])

    ans = 2 * min(data_sum_sei, data_sum_fu) + max(data_sum_sei, data_sum_fu)


    for i in range(start_ind + 1, num - walk_num + 1):
        left_data = data[i - 1]
        right_data = data[i + walk_num - 1]

        if left_data > 0:
            break
        data_sum_fu -= abs(left_data)
        if right_data > 0:
            data_sum_sei += right_data
        else:
            data_sum_fu += abs(right_data)

        ans_kari = 2 * min(data_sum_sei, data_sum_fu) + max(data_sum_sei, data_sum_fu)


        if ans_kari < ans:
            ans = ans_kari

    print(ans)





if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

Submission status: Accepted

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

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):
    if i+K <= N:
        if L[i] < 0:
            if L[K+i-1] > 0:
                cur = min(2*(-L[i])+L[K+i-1],2*(L[K+i-1])-L[i])
                if ans >= cur:
                    ans = cur
            else:
                cur = -L[i]
                if ans >= cur:
                    ans = cur
        else:
            cur = L[i+K-1]
            if ans >= cur:
                ans = cur
print(ans)

Submission status: Accepted

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


def solve(N: int, K: int, x: "List[int]"):
    ret = float('inf')
    for i in range(K - 1, N):
        l = x[i - (K - 1)]
        r = x[i]
        if l < 0 and r > 0:
            tmp = min(abs(l) * 2 + r, abs(l) + r * 2)
            ret = min(ret, tmp)
        else:
            ret = min(ret, max(abs(r), abs(l)))
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    x = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(N, K, x)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

Submission status: Accepted

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

min_time = float("inf")

for i in range(N-K+1):
    if x[i] >= 0:
        time = x[i+K-1]
    if x[i] < 0:
        if x[i+K-1] >= 0:
            time = min(x[i+K-1], -x[i]) + (x[i+K-1] - x[i])
        else:
            time = -x[i]
    min_time = min(min_time,time)
print(min_time)

Submission status: Accepted

Solution code:
import bisect
n, k = [int(item) for item in input().split()]
x = [int(item) for item in input().split()]

lft_num = bisect.bisect(x, 0)
rgt_num = n - lft_num

ans = 10**10
for i in range(min(rgt_num, k)):
    r = x[lft_num + i]
    distance = abs(r)
    if i+1 == k: 
        ans = min(ans, distance)
        continue
    if lft_num - (k-i-1) >= 0:
        l = x[lft_num - (k-i-1)]
        distance += abs(r - l)
        ans = min(ans, distance)
for i in range(min(lft_num, k)):
    l = x[lft_num - i - 1]
    distance = abs(l)
    if i+1 == k: 
        ans = min(ans, distance)
        continue
    if lft_num + (k-i-2) < n:
        r = x[lft_num + (k-i-2)]
        distance += abs(r - l)
        ans = min(ans, distance)
    
print(ans)

Submission status: Accepted

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

answer = 10**9

for i in range(N):
    if i+K-1>= N: break
    answer = min(answer,abs(X[i+K-1]-X[i])+min(abs(X[i]),abs(X[i+K-1])))

print(answer)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def shortest_from_zero(section):
    negative = section[0]
    positive = section[1]
    distance = positive - negative
    return min(distance + abs(negative), distance + positive)


if __name__ == '__main__':
    ans = 100000000000
    n, k = map(int, input().split())
    x_list = list(map(int, input().split()))

    for i in range(n - k + 1):
        section = [min(0, x_list[i]), max(0, x_list[i + k - 1])]
        if ans > shortest_from_zero(section):
            ans = shortest_from_zero(section)
    print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
x=list(map(int,input().split()))
ans=1000000000
for i in range(n-k+1):
  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:
N,K = [int(x) for x in input().split()]
x = [int(x) for x in input().split()]
#%% input
inf = 10**10
ans = inf
for i in range(N-K+1):
    if(x[i+K-1]<0):
        if(len(x)>i+K):
            if(x[i+K]<=0):
                continue
        ans = min(ans,-x[i])
    elif(x[i]>0):
        if(i>0):
            if(x[i-1]>=0):
                continue
        ans = min(ans,x[i+K-1])
    else:
        ans = min(ans,2*x[i+K-1]-x[i],x[i+K-1]-2*x[i])
print(ans)

Submission status: Accepted

Solution code:
#coding: utf-8
N, K = map(int, input().split())
x = list(map(int, input().split()))
ans = 1000000000
for i in range(N-K+1):
    l = x[i]
    r = x[i+K-1]
    tmp = min(abs(l) + abs(r - l), abs(r) + abs(r - l))
    ans = min(ans, tmp)
print(ans)

Submission status: Accepted

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

for i in range(N-K+1):
    L.append(abs(x[i]) + x[K+i-1] - x[i])
    L.append(abs(x[K+i-1]) + x[K+i-1] - x[i])
    
if N != 1:
    print(min(L))
else:
    print(abs(x[0]))

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
Xs = list(map(int,input().split()))
nums = []
for i in range(len(Xs)-K+1):
    left = Xs[i]
    right = Xs[i+K-1]
    nums.append(min(abs(right)+abs(right-left),abs(left)+abs(right-left)))
print(min(nums))

Submission status: Accepted

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

Min = 10**9
for i in range(N-K+1):
    x_l = x[i]
    x_r = x[i+K-1]
    ans_1 = abs(x_l-0) + abs(x_l-x_r)
    ans_2 = abs(x_r-0) + abs(x_l-x_r)
    Min = min(Min, ans_1, ans_2)

print(Min)

Submission status: Accepted

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


if __name__ == '__main__':
    main()