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 collections import deque
    
N,K=map(int,input().strip().split())
x=list(map(int,input().strip().split()))
inf=10**9
    
l=inf
dp=deque(x[N-K:N])
i=0
while True:
    if dp[0]>=0:
        tmp=dp[K-1]
    elif dp[K-1]<=0:
        tmp=-dp[0]
    else:
        if abs(dp[K-1])>=abs(dp[0]):
            tmp=abs(dp[0])*2+abs(dp[K-1])
        else:
            tmp=abs(dp[K-1])*2+abs(dp[0])
    l=min(l,tmp)
    i+=1
    if N-K-i<0:
        break
    else:
        dp.appendleft(x[N-K-i])
        dp.pop()
print(l)

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()))

    INF = float("inf")
    M = [INF] * N
    P = [INF] * N
    i_m, i_p = 0, 0
    for x in X:
        if x == 0:
            K -= 1
        elif x > 0:
            P[i_p] = x
            i_p += 1
        else:
            M[i_m] = -x
            i_m += 1

    if K <= 0:
        print(0)
        exit()

    M.sort()
    P.sort()
    ans = min(M[K - 1], P[K - 1])
    for n_M in range(1, K + 1):
        dist = 2 * M[n_M - 1] + P[K - n_M - 1]
        if ans > dist:
            ans = dist
    for n_P in range(1, K + 1):
        dist = 2 * P[n_P - 1] + M[K - n_P - 1]
        if ans > dist:
            ans = dist

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,K=(int(i) for i in input().strip().split(" "))
x=[int(i) for i in input().strip().split(" ")]
m=1000000000000000000000
for i in range(n-K+1):
    k=-x[i]+x[i+K-1]+min(abs(x[i]),abs(x[i+K-1]))
    if k<m:
        m=k
print(m)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
D = [int(n) for n in input().split()]
ans = 10000000000

for i in range(N-K+1):
    L = D[i]
    R = D[i+K-1]
    LR = abs(L) + abs(L - R)
    RL = abs(R) + abs(R - L)
    ans = min(ans, min(LR, RL))

print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
ls = list(map(int,input().split()))
flag = True
if 0 not in ls:
    ls.append(0)
    ls.sort()
    flag = False
ind = ls.index(0)
if flag == True:
    if ind >= k-1:
        l = ind - k + 1
    else:
        l = 0
    if ind + k - 1 <= n - 1:
        r = ind + k - 1
    else:
        r = n - 1 
    mn = float("inf")
    while True:
        if l+k-1 > r:
            break
        a = abs(ls[l]) + ls[l+k-1] + min(abs(ls[l]),ls[l+k-1])
        if a < mn:
            mn = a
        l += 1
else:
    if ind >= k:
        l = ind - k
    else:
        l = 0
    if ind + k <= n:
        r = ind + k
    else:
        r = n
    mn = float("inf")
    while True:
        if l+k > r:
            break
        a = abs(ls[l]) + ls[l+k] + min(abs(ls[l]),ls[l+k])
        if a < mn:
            mn = a
        l += 1
print(mn)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, K, *X = map(int, read().split())

    A = [abs(x - X[0]) for x in X]

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

    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def solve(N, K, X):
    A = [abs(x - X[0]) for x in X]

    ans = INF
    for i in range(N - K + 1):
        if ans > abs(X[i]) + A[i + K - 1] - A[i]:
            ans = abs(X[i]) + A[i + K - 1] - A[i]

    return ans


def main():
    N, K, *X = map(int, read().split())

    ans = solve(N, K, X)
    ans = min(ans, solve(N, K, X[::-1]))

    print(ans)
    return


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 l in range(n - k + 1):
    r = l + k - 1
    ans = min(ans, abs(x[r]) + abs(x[r]-x[l]), abs(x[l]) + abs(x[r]-x[l]))

print(ans)

Submission status: Accepted

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

ans = 10 ** 10
nega = sorted(-x for x in X if x < 0)
posi = sorted(x for x in X if 0 < x)
if 0 in X:
    K -= 1

if 0 < K <= len(posi):
    t = posi[K - 1]
    ans = min(ans, t)
if 0 < K <= len(nega):
    t = nega[K - 1]
    ans = min(ans, t)

if 0 < K:
    for np in range(1, len(posi) + 1):
        if 0 <= K - np - 1 < len(nega):
            t = posi[np - 1] * 2 + nega[K - np - 1]
            ans = min(ans, t)
    for nn in range(1, len(nega) + 1):
        if 0 <= K - nn - 1 < len(posi):
            t = nega[nn - 1] * 2 + posi[K - nn - 1]
            ans = min(ans, t)
else:
    ans = 0
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
x = list(map(int, input().split()))
ans = abs(x[k-1]) + 2*abs(x[0])
for i in range (n-k+1):
  if 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], 2*x[i+k-1] - x[i])
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n, k, *x = map(int, open(0).read().split())
ans = 10**18
neg = [i for i in x if i<0]+[0]
pos = [0]+[i for i in x if i>=0]
l = len(neg) -max(0, k + 1 - len(pos))
r = min(k+1, len(pos))
while l > 0 and r > 0:
    l -= 1
    r -= 1
    ans = min(ans, -neg[l] * 2 + pos[r], -neg[l] + pos[r] * 2)
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n, k, *x = map(int, open(0).read().split())
ans = 10**18
neg = []
pos = [0]
for i in x:
    if i < 0:
        neg.append(i)
    else:
        pos.append(i)
neg.append(0)
k += 1
c = len(neg)
c -= k -min(k, len(pos))
k = min(k, len(pos))
while c > 0 and k > 0:
    c -= 1
    k -= 1
    ans = min(ans, -neg[c] * 2 + pos[k], -neg[c] + pos[k] * 2)
print(ans)

Submission status: Accepted

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

mt=5*10**8

for i in range(n-k+1):
  mt=min(mt,2*abs(x[i])+abs(x[i+k-1]),abs(x[i])+2*abs(x[i+k-1]))

if x[0]>0:mt=min(mt,x[k-1])
elif x[-1]<0:mt=min(mt,abs(x[-1-k+1]))
print(mt)

Submission status: Accepted

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

import bisect
c=bisect.bisect_left(x,0)
mt=2*10**8

for i in range(n-k+1):
  if i+k<c:continue
  mt=min(mt,2*abs(x[i])+abs(x[i+k-1]),abs(x[i])+2*abs(x[i+k-1]))
  if i+k-1 ==c-1:mt=min(mt,abs(x[i]))
  if i==c:mt=min(mt,x[i+k-1])
if n==k:
  if c!=n and c!=0:
    mt=min(2*abs(x[0])+x[-1],2*x[-1]+abs(x[0]))
  else:
    mt=max(abs(x[0]),abs(x[-1]))
print(mt)

Submission status: Accepted

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

ans=10**10

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

    if left*right>=0:
        ans=min(ans,max(abs(left),abs(right)))
    else:
        ans=min(ans,right-left+min(abs(right),abs(left)))

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[26]:


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


# In[35]:


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


# In[ ]:

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):
    a,b=X[i],X[i+K-1]
    if 0<=a or b<=0:
        M=min(M,max(abs(a),abs(b)))
    else:
        c=min(abs(a),abs(b))
        M=min(M,abs(a)+abs(b)+abs(c))
print(M)

Submission status: Accepted

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

Submission status: Accepted

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

import bisect

b=bisect.bisect_left(x,0)

r=x[b:]
l=list(reversed(x[:b]))


R=len(r)
L=len(l)

ans=float('inf')

if k<=R:
    ans=min(ans,r[k-1])

if k<=L:
    ans=min(ans,abs(l[k-1]))

#右折り返し
for i in range(R):
    if i<k and k-i-2<=L-1 and k-i-2>=0:
        tmp=2*r[i] + abs(l[k-i-2])
        ans=min(ans,tmp)
#左折り返し
for j in range(L):
    if j<k and k-j-2<=R-1 and k-j-2>=0:
        tmp = 2*abs(l[j]) +r[k-j-2]
        ans=min(ans,tmp)


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(0,n-k+1):
  b=a[i]
  c=a[i+k-1]
  if c<=0:
    ans=min(ans,abs(b))
  elif b>=0:
    ans=min(ans,abs(c))
  else:
    ans=min(ans,abs(c)+abs(b)*2,abs(c)*2+abs(b))
    
print(ans)

Submission status: Accepted

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

if len(lis) == 1:
    print(abs(lis[0]))
    exit()

ans = 10**9+7
for i in range(n-k+1):
    l = abs(lis[i]) + abs(lis[i+k-1]-lis[i])
    r = abs(lis[i+k-1]) + abs(lis[i+k-1]-lis[i])
    ans = min(ans, l, r)

print(ans)

Submission status: Accepted

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


l = []
# 連続するK本の選び方について、左端は0,1,2,...,N-K
for i in range(N - K + 1):
    left = i
    right = i + K - 1
    # leftが先、rightが後の場合
    ans1 = abs(x[left]) + abs(x[right] - x[left])
    # rightが先、leftが後の場合
    ans2 = abs(x[right]) + abs(x[right] - x[left])
    tmp_ans = min(ans1, ans2)
    l.append(tmp_ans)

ans = min(l)
print(ans)

Submission status: Accepted

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

INF = 10 ** 18
neg = np.concatenate([-X[X <= 0][::-1], np.full(N+1,INF,dtype=np.int64)])[:K]
pos = np.concatenate([X[X > 0], np.full(N+1,INF,dtype=np.int64)])[:K]

answer = INF
# 左のみ
answer = min(answer, neg[-1])
# 右のみ
answer = min(answer, pos[-1])
if K >= 2:
  # 左にa個、右にK-a個
  answer = min(answer, (neg[:K-1] * 2 + pos[K-2::-1]).min())
  # 右にa個、右にK-a個
  answer = min(answer, (pos[:K-1] * 2 + neg[K-2::-1]).min())

print(answer)

Submission status: Accepted

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

# R = [x[i] for i in range(N) if x[i] >= 0]
# L = [abs(x[i]) for i in range(N-1, -1, -1) if x[i] < 0]

# len_R = len(R)
# len_L = N - len_R
# r = 0
# l = 0
# time = 1e10

# dp_r = [0] * (len_R + 1) #右サイドでi個選んだ時のコストdp[i]
# dp_l = [0] * (len_L + 1)

# for i in range(1, N-1):
#     dp_r[i] = min(dp_r[i-1] + R[i])
def cost(i):
    l = i
    r = i+K
    if x[l] >= 0:
        return abs(x[r-1])
    elif x[r-1] <= 0:
        return abs(x[l])
    else:
        if abs(x[l]) < abs(x[r-1]):
            return 2*abs(x[l]) + abs(x[r-1])
        else:
            return 2*abs(x[r-1]) + abs(x[l])
ans = 1e12
for i in range(0, N-K+1):
    ans = min(ans, cost(i))
print(ans)

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,K=(int(i) for i in input().strip().split(" "))
x=[int(i) for i in input().strip().split(" ")]


ans = min(b - a + min(abs(a), abs(b)) for a, b in zip(x, x[K-1:]))
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
x = list(map(int, input().split()))
minus = [0]
plus = [0]
for i in x:
    if x:
        plus.append(x)
    else:
        minus.append(-x)
k -= 1
ans = 1000000000000000
for i in range(n-k):
    if x[i+k] < 0:
        ans = min(ans, -x[i])
    elif 0 < x[i+k] and x[i] < 0:
        if -x[i] < x[i+k]:
            ans = min(ans, abs(2*(x[i])) + x[i+k])
        else:
            ans = min(ans, 2*x[i+k] + abs(x[i]))
    else:
        ans = min(ans, x[i+k])
    
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
import math
import bisect
import numpy as np
N, k = map(int,input().split())
X = list(map(int,input().split()))
#if 0 in X:
 #   k -= 1
ans = float('inf')
for i in range(N-k+1):
    a = X[i]
    b = X[i+k-1]
    #print(a, b)
    if np.sign(a)*np.sign(b) >= 0:
        ans = min(ans, max(abs(a), abs(b)))
        #print("d="+str(max(abs(a), abs(b))))
    else:
        ans = min(ans, abs(a)+abs(b)+min(abs(a), abs(b)))
        #print("d="+str(abs(a)+abs(b)))
print(ans)

Submission status: Accepted

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

ans = 10 ** 9
for l in range(0, n - k + 1):
  r = l + k - 1
  a = abs(x[r]) + abs(x[r] - x[l])
  b = abs(x[l]) + abs(x[r] - x[l])
  ans = min(ans, min(a, b))

print(ans)

Submission status: Accepted

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

inf = 10**12
z = len(x)

if n == 1 and k == 1:
    print(0)
    exit()

for i in range(len(x)):
    if x[i] >= 0:
        z = i
        break

r = [inf] * (n - z)
l = [inf] * z

for i in range(n-z):
    r[i] = x[z+i]

for i in range(z):
    l[i] = abs(x[z-i-1])

# 左からすべて取る場合
tl = inf
if len(l) < k:
    tl = inf
else:
    tl = abs(l[k-1])

if z == n-1:
    print(tl)
    exit()

# 右からすべて取る場合
tr = inf
if len(r) < k:
    tr = inf
else:
    tr = abs(r[k-1])
    
# 両方から取る場合
# 右からi個取る
t_arr = []
for i in range(1,k):
    if i-1 >= len(r):
        pass
    else:
        if k-i-1 >= len(l):
            pass
        else:
            t1 = r[i-1]
            t2 = l[k-i-1]
            t_arr.append(t1*2 + t2*2 - max(t1,t2))
tc = inf
if len(t_arr) != 0:
    tc = min(t_arr)
else:
    tc = inf
print(min(tl,tr,tc))

Submission status: Accepted

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

ans =[]
if arr[0]>0:
    ans.append(arr[K-1])

if arr[-1]<0:
    ans.append(abs(arr[-1*(K)]))

for i in range(N-K+1):
    if arr[i]*arr[i+K-1]<=0:
        left =2*abs(arr[i])+abs(arr[i+K-1])
        right=2*abs(arr[i+K-1])+abs(arr[i])
        ans.append(min(left,right))

print(min(ans))

Submission status: Accepted

Solution code:
def main():
    n,k = map(int,input().split())
    x = list(map(int,input().split()))
    m,p = [],[]
    for i in range(n):
        if x[i]<0:
            m.append(x[i])
        else:
            p.append(x[i])
    M,P = len(m),len(p)
    ans = float('inf')
    for i in range(min(M+1,k+1)):
        t = 0
        if i>0:
            t += 2*abs(m[M-i])
        r = k-i
        if r==0:
            if t//2<ans:
                ans = t//2
        elif r<=P:
            t += p[r-1]
            if t<ans:
                ans = t
    for i in range(min(P+1,k+1)):
        t = 0
        if i>0:
            t += 2*p[i-1]
        r = k-i
        if r==0:
            if t//2<ans:
                ans = t//2
        elif r<=M:
            t += abs(m[M-r])
            if t<ans:
                ans = t
    print(ans)

if __name__ == "__main__":
    main()

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

Submission status: Accepted

Solution code:
# 初期入力 2020-0730-2150
from bisect import bisect_left
import sys
input = sys.stdin.readline  #文字列では使わない
N,K = map(int, input().split())
x = list(map(int, input().split()))
x_shift =[i +abs(x[0]) for i in x]
 
dist =[]
for i in range(N-K+1):
    d_end =x_shift[i+K-1] -x_shift[i] #ローソクK本の内、端と端の距離
    d_left =abs(x[i])
    d_right =abs(x[i+K-1])
    dist.append(d_end +min(d_left,d_right))
print(min(dist))

Submission status: Accepted

Solution code:
# 初期入力 2020-0730-2150
from bisect import bisect_left
import sys
input = sys.stdin.readline  #文字列では使わない
N,K = map(int, input().split())
x = list(map(int, input().split()))
x_shift =[i +abs(x[0]) for i in x]
bis_0 =bisect_left(x,0)
 
d_end =[0]*(N-K+1)
d_left =0
d_right =0
dist =[]
for i in range(N-K+1):
    d_end =x_shift[i+K-1] -x_shift[i] #ローソクK本の内、端と端の距離
    d_left =abs(x[i])
    d_right =abs(x[i+K-1])
    dist.append(d_end +min(d_left,d_right))
print(min(dist))

Submission status: Accepted

Solution code:
if __name__ == '__main__':

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

	ans = float("inf")

	for i in range(k+1):
		if i+k > n:
			break

		left = A[i]
		right = A[i+k-1]

		#1 abs(left) < abs(right) の場合
		tmp2 = abs(left) + abs(right - left)

		#2 abs(right) > abs(left)の場合
		tmp3 = abs(right) + abs(left - right)

		ans = min(ans,min(tmp2,tmp3))

	print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

# index = bisect.bisect(list, 0)

# left = index
# right = n - index

# if left != 0:
#     if x[index-1] == 0:
#         k -= 1
#         del(x[index-1])

ans = 10**9
for i in range(0, n-k+1):
    # print(x[i], x[i+k-1])
    if x[i]*x[i+k-1] >= 0:
        ans_tmp = max(abs(x[i]), abs(x[i+k-1]))
    else:
        ans_tmp = abs(x[i]) + abs(x[i+k-1]) + min(abs(x[i]), abs(x[i+k-1]))

    # print(ans_tmp)
    ans = min(ans, ans_tmp)
# print()
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import bisect
import math

N,K = map(int, input().split())
X = list(map(int, input().split()))
a = bisect.bisect_left(X,0)
X.insert(a,0)

ans = math.inf

for i in range(max(0,a+K-N), min(a+1,K+1)):
    ans = min(ans, -X[a-i]*2+X[a+K-i], -X[a-i]+X[a+K-i]*2)

print(ans)

Submission status: Accepted

Solution code:
N,K = list(map(int,input().split()))
x = list(map(int,input().split()))
minTime = 10000000000
for i in range(N-K+1):
    time = 0
    minValue = x[i]
    maxValue = x[i+K-1]
    if minValue < 0 and maxValue < 0:
        time = minValue * -1
    elif minValue >= 0 and maxValue >= 0:
        time = maxValue
    elif minValue < 0 and maxValue >= 0:
        leftTime = minValue * -1
        rightTime = maxValue
        if leftTime < rightTime:
            time = leftTime * 2 + rightTime
        else:
            time = leftTime + rightTime * 2
    if time < minTime:
        minTime = time
print(minTime)

Submission status: Accepted

Solution code:
N,K = (int(T) for T in input().split())
X = [int(T) for T in input().split()]
Cost = [0]*(N-K+1)
for T in range(0,N-K+1):
    Left  = X[T]
    Right = X[T+K-1]
    Cost[T] = min(abs(Left)+abs(Left-Right),abs(Right)+abs(Right-Left))
print(min(Cost))

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N, K = mapint()
Xs = list(mapint())

pos = []
neg = []

for x in Xs:
    if x>=0:
        pos.append(x)
    else:
        neg.append(-x)

neg = neg[::-1]

ans = 10**18
if len(pos)>=K:
    ans = min(ans, pos[K-1])
if len(neg)>=K:
    ans = min(ans, neg[K-1])
lenp = len(pos)
lenn = len(neg)
if lenn>0:
    for i in range(min(lenp, K)):
        if K-(i+1)<=lenn:
            ans = min(ans, pos[i]*2+neg[K-i-2])
if lenp>0:
    for i in range(min(lenn, K)):
        if K-(i+1)<=lenp:
            ans = min(ans, neg[i]*2+pos[K-i-2])
print(ans)

Submission status: Accepted

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

ans = float('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, X[r])
    else:
        ans = min(ans, abs(X[l]) + X[r] + min(abs(X[l]), X[r]))


print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys

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

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

    
if __name__ == '__main__':
    main()

Submission status: Accepted

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

# C - Candles /
# 実行時間制限: 2 sec / メモリ制限: 1024 MB
# 配点 : 300点

# 問題文
# 数直線上に N本のろうそくが置かれています。 
# 左から i 番目のろうそくは座標 xi に置かれています。 ただし、x1<x2<...<xNが成り立ちます。
# 最初、どのろうそくにも火が付いていません。 すぬけ君は、N本のうち K本のろうそくに火を付けることにしました。
# 今、すぬけ君は座標 0にいます。 すぬけ君は、数直線上を左右に速度 1で移動することができます。 
# また、自分と同じ座標のろうそくに火を付けることができます。 このとき、火を付けるのに掛かる時間は無視できます。
# K本のろうそくに火を付けるのに必要な最小の時間を求めてください。

# 制約
#     1≤N≤105
#     1≤K≤Nxiは整数である。
#     |xi|≤108x1<x2<...<xN

# 入力
# 入力は以下の形式で標準入力から与えられる。
# N K
# x1 x2 ... xN

# 出力
# K本のろうそくに火を付けるのに必要な最小の時間を出力せよ。

# 入力例 1
# 5 3
# -30 -10 10 20 50

# 出力例 1
# 40

# 次のように移動しながらろうそくに火を付ければよいです。

#     座標 0から −10へ移動する。
#     左から 2番目のろうそくに火を付ける。
#     座標 −10から 10へ移動する。
#     左から 3番目のろうそくに火を付ける。
#     座標 10から 20へ移動する。
#     左から 4番目のろうそくに火を付ける。

# 入力例 2
# 3 2
# 10 20 30

# 出力例 2
# 20

# 入力例 3
# 1 1
# 0

# 出力例 3
# 0

# 座標 0にろうそくが置かれていることもあります。

# 入力例 4
# 8 5
# -9 -7 -4 -3 1 2 3 4

# 出力例 4
# 10


def calculation(lines):
    N, K = list(map(int, lines[0].split()))
    values = list(map(int, lines[1].split()))
    # 取りうるパターン数
    P = N-K+1
    difs = list()
    for p in range(P):
        LL = values[p]
        r = values[K-1+p]
        rev = 0
        if LL*r < 0:
            rev = min(abs(LL), abs(r))
            dif = (r-LL) + rev
        else:
            dif = max(abs(r), abs(LL))
        difs.append(dif)
    return [min(difs)]


# 引数を取得
def get_input_lines(lines_count):
    lines = list()
    for _ in range(lines_count):
        lines.append(input())
    return lines


# テストデータ
def get_testdata(pattern):
    if pattern == 1:
        lines_input = ['5 3', '-30 -10 10 20 50']
        lines_export = [40]
    if pattern == 2:
        lines_input = ['3 2', '10 20 30']
        lines_export = [20]
    if pattern == 3:
        lines_input = ['1 1', '0']
        lines_export = [0]
    if pattern == 4:
        lines_input = ['8 5', '-9 -7 -4 -3 1 2 3 4']
        lines_export = [10]
    return lines_input, lines_export


# 動作モード判別
def get_mode():
    import sys
    args = sys.argv
    if len(args) == 1:
        mode = 0
    else:
        mode = int(args[1])
    return mode


# 主処理
def main():
    mode = get_mode()
    if mode == 0:
        lines_input = get_input_lines(2)
    else:
        lines_input, lines_export = get_testdata(mode)

    lines_result = calculation(lines_input)

    for line_result in lines_result:
        print(line_result)

    # if mode > 0:
    #     print(f'lines_input=[{lines_input}]')
    #     print(f'lines_export=[{lines_export}]')
    #     print(f'lines_result=[{lines_result}]')
    #     if lines_result == lines_export:
    #         print('OK')
    #     else:
    #         print('NG')


# 起動処理
if __name__ == '__main__':
    main()

Submission status: Accepted

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

for n in range(N-K+1):
  A+=[X[n+K-1]-X[n]+min(abs(X[n]),abs(X[n+K-1]))]

print(min(A))

Submission status: Accepted

Solution code:

def solve():
    n, k = [int(x) for x in input().split()]
    a = [int(x) for x in input().split()]
    ans = float('inf')
    for i in range(n):
        if i + 1 >= k:
            l = a[i - k + 1]
            r = a[i]
            ans = min(ans, r - l + min(abs(l), abs(r)))
    print(ans)

solve()

"""
5 6
4 7 9 3 4
"""

Submission status: Accepted

Solution code:
import bisect
n,k = map(int,input().split())
a = list(map(int,input().split()))
# for i in a[0:bisect.bisect_left(t,0)]:
m = a[0:bisect.bisect_left(a,0)]+[0]
p = [0]+a[bisect.bisect_left(a,0):]
# for i in range(len(m)-2,-1,-1):
#     m[i] += m[i+1]
# for i in range(1,len(p)):
#     p[i] += p[i-1]
# print(p)
# print(m)
ans = 10**9
for i in range(max(k-len(m)+1,0),min(len(p),k+1)):
    ans = min(ans,2*p[i]+abs(m[-(k-i+1)]))
    # print(ans,i,-(k-i+1),p[i],abs(m[-(k-i)]))
for i in range(max(k-len(p)+1,0),min(len(m),k)):
    ans = min(ans,2*abs(m[-i-1])+abs(p[k-i]))
    # print(ans,i,(k-i),abs(m[-i-1]),abs(p[k-i]))
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):
    sm=x[i]
    sp=x[i+k-1]
    if sp<0:
        ans=min(-sm,ans)
    elif 0<sm:
        ans=min(ans,sp)
    else:
        ans=min(ans,min(sm*-2+sp,sp*2-sm))
print(ans)

Submission status: Accepted

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

p = []
m = []
for i in a:
    if i >= 0:
        p.append(i)
    else:
        m.insert(0,-i)
p.insert(0,0)
m.insert(0,0)

ans = 10**9
for i in range(k+1):
    if i < len(p) and k-i < len(m):
        d_p = p[i]
        d_m = m[k-i]
        d = min(d_p,d_m)*2 + max(d_p,d_m)
        ans = min(ans,d)

print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

ans = float('inf')
for i in range(n - k + 1):
    right = x[i + k - 1]
    left = x[i]
    if right <= 0:
        time = abs(left)
    elif left <= 0 < right:
        time = abs(right-left)
        time += min(abs(right), abs(left))
    elif 0 < left:
        time = abs(right)
    ans = min(ans, time)
print(ans)

Submission status: Accepted

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

# mapping [X0...] [Xk-1...] by zip
#for a, b in zip(x, x[K-1:]):
#    print(a, b)
# the answer is the minimum number of Xi+k$B!](B1 $B!](B Xi + min(|Xi|,|Xi+k$B!](B1|) 
# the initial distance is always coordinate 0
ans = min(b - a + min(abs(a), abs(b)) for a, b in zip(x, x[K-1:]))
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
lst=list(map(int,input().split()))
ans=float("inf")
for i in range(n-k+1):
    left=lst[i]
    right=lst[i+k-1]
    if left==0 and right==0:
        print(0)
        exit()
    if left<0 and right<=0:
        ans=min(ans,abs(left))
    elif left<0 and right>0:
        if abs(left)>abs(right):
            ans=min(ans,abs(left)+right*2)
        else:
            ans=min(ans,abs(left)*2+right)
    else:
        ans=min(ans,right)
print(ans)

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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

left = 0
right = K - 1

ans = INF
while right < len(X):
    val1 = abs(X[left]) + abs(X[right] - X[left])
    val2 = abs(X[right]) + abs(X[right] - X[left])
    ans = min(ans, val1, val2)
    left += 1
    right += 1
print(ans)

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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

left = 0
right = K - 1

ans = INF
while right < len(X):
    if X[right] <= 0:
        ans = min(ans, abs(X[left]))
    elif X[left] >= 0:
        ans = min(ans, X[right])
    else:
        val1 = abs(X[left] - 0) * 2 + abs(X[right] - 0)
        val2 = abs(X[right] - 0) * 2 + abs(X[left] - 0)
        ans = min(ans, val1, val2)
    left += 1
    right += 1
print(ans)

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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

ps = [0] + list(filter(lambda x: x >= 0, X))
ns = [0] + list(sorted(filter(lambda x: x < 0, X), reverse=True))

ans = INF
for i in range(len(ns)):
    val = abs(ns[i]) * 2
    if K - i >= 0 and K - i < len(ps):
        val += abs(ps[K - i])
        ans = min(ans, val)

for i in range(len(ps)):
    val = abs(ps[i]) * 2
    if K - i >= 0 and K - i < len(ns):
        val += abs(ns[K - i])
        ans = min(ans, val)
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(K-1,N):
    xl = X[i-K+1]
    xr = X[i]
    ans = min(abs(xr)+abs(xr-xl),abs(xl)+abs(xr-xl),ans)
print(ans)