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: Time Limit Exceeded

Solution code:
N,K=map(int,input().split(' '))
x = list(map(int,input().split(' ')))
ans = 2*(10**8)
if N==K:
    if x[-1]<0:
        print(-x[0])
    elif x[0]>0:
        print(x[-1])
    else:
        print(min(x[-1]-2*x[0],2*x[-1]-x[0]))
    exit()
for i in range(N-K):
    tmp = x[i:i+K]
    if tmp[-1]<0:
        ans = min(ans,-tmp[0])
    elif tmp[0]>=0:
        ans = min(ans,tmp[-1])
    else:
        ans = min(ans,tmp[-1]-2*tmp[0],2*tmp[-1]-tmp[0])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math

S = input().split(" ")
N = int(S[0])
K = int(S[1])

arr = [int(s) for s in input().split(" ")]


def calculate(n, k, arr):
    minsArr = []
    plusArr = []
    for ar in arr:
        if ar < 0:
            minsArr.append(ar)
        else:
            plusArr.append(ar)

    # find start index
    startIndex = -10000

    if len(minsArr) > k:
        startIndex = len(minsArr) - k
    else:
        startIndex = 0

    minValues = []
    while startIndex <= len(minsArr):
        tmpArr = arr[startIndex:startIndex + k]
        if len(tmpArr) < k:
            break
        minValue = 0

        if tmpArr[0] * tmpArr[-1] < 0:
            minValue = math.fabs(tmpArr[-1] - tmpArr[0]) + min(math.fabs(tmpArr[-1]), math.fabs(tmpArr[0]))
            a = 1
        else:
            #全部为正数
            if tmpArr[0] >= 0:
                minValue = math.fabs(tmpArr[-1])
            #全部为负数
            else:
                minValue = math.fabs(tmpArr[0])


        minValues.append(minValue)
        startIndex = startIndex + 1

    return int(min(minValues))


result = calculate(N, K, arr)
print(result)

Submission status: Time Limit Exceeded

Solution code:
def main():
    n,k=map(int,input().split())
    X=list(map(int,input().split()))
    cnt=0
    Xp,Xz,Xm=0,False,0
    for x in X:
        if x<0:
            cnt+=1
        elif x==0:
            Xm=X[:cnt]
            Xz=True
            Xp=X[cnt+1:]
        else:
            Xm=X[:cnt]
            Xp=X[cnt:]
    if Xp==0:
      Xm=X
      Xp=[]
    lp,lm=len(Xp),len(Xm)

    if Xz:
        k-=1
    if k==0:
      print(0)
      exit()
      
    ans=10**9
    if k<=lp:
        ans=min(ans,Xp[k-1])
    if k<=lm:
        ans=min(ans,-Xm[-k])

    for i in range(lp):
        j=k-i-1
        if 0<j<=lm:
            ans=min(ans,Xp[i]*2-Xm[-j])
        else:
            continue
        
    for i in range(lm,0,-1):
        j=k-i-1
        if 0<=j<lp:
            ans=min(ans,Xm[-i]*(-2)+Xp[j])
        else:
            continue
    print(ans)
   
if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

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

s = 10**9
for i in range(n-k+1) :
  f = x[i:i+k] 
  m = min(abs(f[0]) +abs(f[-1] - f[0]) , abs(f[-1]) + abs(f[-1] - f[0]))
  if s >m :
    s = m
print(s)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(2000000)

def two_int():
    N, K = map(int, input().split())
    return N,K

def one_int():
    return int(input())

def one_str():
    return input()

def many_int():
    return list(map(int, input().split()))
# import sys
# input = sys.stdin.readline

import bisect

N,K=two_int()
X=many_int()

def dfs(left_index, right_index, now_index, score, count):
#     print(left_index, right_index, now_index, score, count)

    if count==K:
#         print(left_index, right_index, now_index, score, count)
        return score
    
    right =10**10
    left  =10**10
    
    if right_index+1<len(X):
        right = dfs(left_index, right_index+1, right_index+1, 
                   score+abs(X[right_index+1]-X[now_index]), count+1)
        
    if left_index-1>=0:
        left = dfs(left_index-1, right_index, left_index-1, 
                    score+abs(X[now_index]-X[left_index-1]), count+1)
    

    return min(right,left)

zero_index = bisect.bisect_left(X,0)



count=0
if  bisect.bisect_right(X,0)==zero_index:
    bisect.insort_left(X,0)


# print(zero_index, count)

# X

if len(X)==1 and X[0]==0:
    print(0)
else:
    print(dfs(zero_index, zero_index, zero_index, 0, count))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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


def min_for_interval(interval):
    left = interval[0]
    right = interval[-1]

    if left < 0:
        if right < 0:
            return abs(left)
        else:
            l_r = 2 * abs(left) + abs(right)
            r_l = 2 * abs(right) + abs(left)
            return min(l_r, r_l)
    else:
        return right


min_time = 1e9
for i in range(0, n - k + 1):
    interval = xs[i:i + k]
    min_time = min(min_for_interval(interval), min_time)

print(min_time)

Submission status: Time Limit Exceeded

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

answer = []
for i in range(N):
  if i + K > N:
    break
  Y = X[i:i+K]
  if Y[0] > 0:
    answer.append(Y[-1])
  elif Y[-1] < 0:
    answer.append(-Y[0])
  else:
    answer.append(min(Y[0]*(-2)+Y[-1], Y[-1]*2-Y[0]))

print(min(answer))

Submission status: Time Limit Exceeded

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

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

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

ans = INF
for i in range(K):
    if i+K > N:
        break
    A2 = A[i:i+K]
    l = A2[0]
    r = A2[-1]
    # 左だけ行く
    if r <= 0:
        ans = min(ans, -l)
    # 右だけ行く
    elif l >= 0:
        ans = min(ans, r)
    # 両方行く
    else:
        # 短い方を先に行って往復
        ans = min(ans, min(-l, r) * 2 + max(-l, r))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations

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

c = combinations(x, k)

# print(list(c))

ans = 10 ** 10

for g in c:
    a = max(0, max(g))
    b = min(0, min(g))
    # print(a, b)
    if (a * b) < 0:
        tmp = min(2 * abs(a) + abs(b), 2 * abs(b) + abs(a))
    else:
        tmp = abs(a) + abs(b)
    ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
l = list(map(int, input().split()))
ans = 9999999999999
for i in range(len(l) - k + 1):
    tl = l[i:i + k]
    min_l = min(0, tl[0])
    max_l = max(0, tl[-1])
    min_abs = min(abs(min_l), abs(max_l))
    max_abs = max(abs(min_l), abs(max_l))
    ans = min(ans, min_abs * 2 + max_abs)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
l = list(map(int, input().split()))
ans = 9999999999999
for i in range(len(l) - k + 1):
    tl = l[i:i + k]
    min_l = min(0, min(tl))
    max_l = max(0, max(tl))
    min_abs = min(abs(min_l), abs(max_l))
    max_abs = max(abs(min_l), abs(max_l))
    ans = min(ans, min_abs * 2 + max_abs)
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
N , K = map(int,input().split())
x = list(map(int,input().split()))
ans = float("inf")
for i in range(N - K + 1):
    search_candles = x[i : i + K]
    if search_candles[-1] <= 0:
        tmp_min = abs(search_candles[0])
    elif 0 <= search_candles[0]:
        tmp_min = abs(search_candles[-1])
    else:
        PassTwice = min(abs(search_candles[-1]) ,abs(search_candles[0])) * 2
        PassOnce = max(abs(search_candles[-1]) ,abs(search_candles[0]))
        tmp_min = PassTwice + PassOnce
    if tmp_min < ans:
        ans = tmp_min
print(ans)

Submission status: Time Limit Exceeded

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

def solve(N: int, K: int, x: "List[int]"):
    x = np.array(x)
    score = 10**9
    x_s = sorted(x[x < 0], reverse=True)
    x_len_plus = len(x[x >= 0])
    x_len_minus = len(x[x < 0])
    for right in range(min(K + 1, x_len_plus + 1)):
        left = min(K - right, max(0, x_len_minus))
        if right + left == K:
            rpath = 0
            lpath = 0
            if x_len_plus > 0:
                rpath = x[x >= 0][right - 1]
            if x_len_minus > 0:
                lpath = abs(x_s[left - 1])
            score = min(score, rpath + lpath + min(rpath, lpath))

    print(score)


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    N, K = map(int, input().split())
    x = list(map(int, input().split()))
    solve(N, K, x)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def solve(N: int, K: int, x: "List[int]"):
    x = np.array(x)
    score = 10**9
    for right in range(min(K + 1, len(x[x >= 0])+1)):
        left = min(K - right, max(0, len(x[x < 0])))
        if right + left == K:
            rpath = 0
            lpath = 0
            if len(x[x >= 0]) > 0:
                rpath = x[x >= 0][right - 1]
            if len(x[x < 0]) > 0:
                lpath = abs(sorted(x[x < 0], reverse=True)[left - 1])
            score = min(score, rpath + lpath + min(rpath, lpath))

    print(score)


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    N, K = map(int, input().split())
    x = list(map(int, input().split()))
    solve(N, K, x)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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 permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect

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()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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


ans = INF
idx = bisect(x, 0)
for i in range(idx-K, idx+1):
	if 0 <= i <= N-K:
		l = x[i:i+K]
		if i == idx-K:
			ans = min(ans, abs(x[i]))
		elif i == idx:
			ans = min(ans, x[i+K-1])
		else:
			ans = min(ans, 2*abs(x[i])+x[i+K-1], abs(x[i])+2*x[i+K-1])
print(ans)

Submission status: Time Limit Exceeded

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 permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect

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()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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


ans = INF
idx = bisect(x, 0)
for i in range(idx-K, idx+1):
	if 0 <= i <= N-K:
		l = x[i:i+K]
		if i == idx-K:
			ans = min(ans, abs(l[0]))
		elif i == idx:
			ans = min(ans, l[-1])
		else:
			ans = min(ans, 2*abs(l[0])+l[-1], abs(l[0])+2*l[-1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#                         author:  kagemeka 
#                         created: 2019-11-09 16:39:51(JST)
### modules
## from standard library
import sys
# import collections
# import math
# import string
import bisect
# import re
# import itertools
# import statistics
# import functools
# import operator
## from external libraries
# import scipy.special   
# import scipy.misc      
# import numpy as np 

def main():
    n, k, *x = (int(i) for i in sys.stdin.read().split())

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


if __name__ == "__main__":
    # execute only if run as a script
    main()

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
right, left = [], []
	
for i in range(N):
	if X[i] >= 0:
		right.append(X[i])
	else:
		left.insert(0, -X[i])
		
right.append(0)
left.append(0)
ans = float("inf")
		
for i in range(K + 1):
	if len(right) < K - i + 1 or len(left) < i + 1: continue
	tmp = min(2 * left[i - 1] + right[(K - i) - 1], left[i - 1] + 2 * right[(K - i) - 1])
	ans = min(ans, tmp)
	
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

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


for distance in range(100000000):
    a = bisect.bisect_left(x, -distance)
    b = bisect.bisect_right(x, distance)
    near_k = b- a
    if near_k == k:
        break
    elif near_k > k:
        if x[a]+1 in x:
            a += 1
            break
        elif x[b-1] - 1 in x:
            b -= 1
            break

if x[b-1] * x[a] < 0:
    semi_final_distance = max(x[b-1], x[a])+ (-2 * min(x[b-1], x[a]))
else:
    semi_final_distance = max(x[b-1], x[a])

a_2 = bisect.bisect_left(x, -semi_final_distance)
b_2 = bisect.bisect_right(x, semi_final_distance)
c = bisect.bisect_left(x, 0)
if b_2 - c > k:
    for distance in range(semi_final_distance):
        b_3 = bisect.bisect_right(x, distance)
        if b_3 - c == k:
            print(distance)
            exit()
elif c - a_2 > k:
    for distance in range(semi_final_distance):
        a_3 = bisect.bisect_left(x, -distance)
        if c - a_3 == k:
            print(distance)
            exit()
else:
    print(semi_final_distance)

Submission status: Time Limit Exceeded

Solution code:
import sys


def solve():
    sys.setrecursionlimit(2000)
    input = sys.stdin.readline
    mod = 10 ** 9 + 7
    n, k = list(map(int, input().rstrip('\n').split()))
    x = list(map(int, input().rstrip('\n').split()))
    if len(x) == 1:
        print(abs(sum(x)))
    else:
        mt = 10 ** 10
        for i in range(k, n+1):
            tx = x[i-k:i]
            if tx[0] * tx[-1] < 0:
                mt = min(mt, abs(tx[0]) + abs(tx[-1]) + min(abs(tx[0]), abs(tx[-1])))
            else:
                mt = min(mt, max(abs(tx[0]), abs(tx[-1])))
        print(mt)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

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

for i in range(N-K+1):
    L=X[i:i+K]
    if L[0]>0 and L[0]*L[-1]>0:
        ans=min(ans,L[-1])
    elif L[0]<0 and L[0]*L[-1]>0:
        ans=min(ans,-L[0])
    else:
        ans=L[-1]-L[0]+min(L[-1],-L[0])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
import bisect

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

zero=bisect.bisect_left(X,0)

ans=10**18
start=max(0,zero-K)
for i in range(start,start+N-K+1):
    temp=X[i:i+K]
    m=min(0,min(temp))
    M=max(0,max(temp))
    ans=min((abs(m)+abs(M)*2),(abs(m)*2+abs(M)),ans)
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
ary = [0] + list(map(int, input().split()))
ary = sorted(ary)
a = ary.index(0)
ans = float("Inf")
for i in range(N + 1):
    if i == a: continue

    k = abs(i - a)
    d = abs(ary[i])
    if k >= K and ans > d:
        ans = d
    if i < a:
        k = K - abs(i - a)
        d = abs(ary[i])
        if 0 < k < len(ary[a:]):
            d += abs(ary[i] - ary[k + a])
            if ans > d:
                ans = d

print(0 if ans == float("Inf") else ans)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
ary = [0]+list(map(int,input().split()))
dp = [[0]*(N+1) for _ in range(N+1)]
ary = sorted(ary)
a = ary.index(0)
ans = float("Inf")
for i in range(N+1):
    for j in range(N+1):
        dp[i][j] = abs(ary[i]-ary[j])
for i in range(N+1):
        if i == a:continue
        k = abs(i - a)
        d = abs(ary[i])
        if k >= K and ans > d:
            ans = d
        if i <= a:
            k = K - abs(i-a)
            d = abs(ary[i])
            if k > 0:
                d += dp[i][a+k]
                if ans > d:
                    ans = d
print(0 if ans == float("Inf") else ans)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
ary = [0]+list(map(int,input().split()))
dp = [[0]*N for _ in range(N)]
check = [[False]*N for _ in range(N)]
ary = sorted(ary)
a = ary.index(0)
ary.pop(a)
ans = float("Inf")
for i in range(N):
    for j in range(N):
        dp[i][j] = [abs(ary[i]-ary[j]),abs(j-i)]
for i in range(N):
    for j in range(i,N):
        if i <= j <= a-1:continue
        if i == j:
            k = abs(dp[i][i][1] - a)
            d = abs(ary[i])
            if k >= K and ans > d:
                ans = d
            continue

        k = 1 + dp[i][j][1]
        d = abs(ary[i]) + dp[i][j][0]
        if k >= K and ans > d:
            ans = d
print(0 if ans == float("Inf") else ans)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
ary = [0]+list(map(int,input().split()))
dp = [[0]*N for _ in range(N)]
ary = sorted(ary)
a = ary.index(0)
ary.pop(a)
ans = float("Inf")
for i in range(N):
    for j in range(N):
        dp[i][j] = [abs(ary[i]-ary[j]),abs(j-i)]
for i in range(N):
    for j in range(i,N):
        if i == j:
            k = abs(dp[i][i][1] - a)
            d = abs(ary[i])
            if k >= K and ans > d:
                ans = d
            continue
        k = 1 + dp[i][j][1]
        d = abs(ary[i]) + dp[i][j][0]
        if k >= K and ans > d:
            ans = d
print(0 if ans == float("Inf") else ans)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
ary = [0]+list(map(int,input().split()))
dp = [[0]*N for _ in range(N)]
ary = sorted(ary)
a = ary.index(0)
ary.pop(a)
ans = float("Inf")
for i in range(N):
    for j in range(N):
        dp[i][j] = [abs(ary[i]-ary[j]),abs(j-i)]
for i in range(N):
    for j in range(N):
        if i == j:
            k = abs(dp[i][i][1] - a)
            d = abs(ary[i])
            if k >= K and ans > d:
                ans = d
            continue
        k = 1 + dp[i][j][1]
        d = abs(ary[i]) + dp[i][j][0]
        if k >= K and ans > d:
            ans = d
print(0 if ans == float("Inf") else ans)

Submission status: Time Limit Exceeded

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

cost=10**10

Plus=[i for i in X if i>=0]
Minus=[-i for i in X if i<=0]

if len(Plus)>=K:
    cost=Plus[K-1]
if len(Minus)>=K:
    cost=min(cost,Minus[-K])

i=0
while X[i]<0 and i+K-1<N:
    L=[j-X[i] for j in X]
    cost=min(cost,L[i+K-1]+abs(X[i]))
    i+=1

print(cost)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

dist = []
for i in range(N-K+1):
    t = 0
    tmp = x[i:i+K]
    l, r = tmp[0], tmp[-1]
    
    t = min(abs(l)+abs(l-r), abs(r)+abs(r-l))

    dist.append(t)

print(min(dist))

Submission status: Time Limit Exceeded

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

dist = []
for i in range(N-K+1):
    a = 0
    tmp = x[i:i+K]
    mini, maxi = tmp[0], tmp[-1]
    if (mini >= 0 and maxi >= 0):
        a = maxi
    elif (mini < 0 and maxi < 0):
        a = abs(mini)
    if mini < 0 and maxi >= 0:
        a = abs(mini) + maxi + min(abs(mini), maxi)
    dist.append(a)

print(min(dist))

Submission status: Time Limit Exceeded

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

ans = float('inf')
for i in range(len(cand)):
  l = cand[i][0]
  r = cand[i][-1]
  temp = min(abs(l)+abs(r-l),abs(r)+abs(l-r))
  ans = min(temp,ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations
N,K = map(int,input().split())
x = list(map(int,input().split()))
cand = list(combinations(x, K))
ans = float('inf')
for i in range(len(cand)):
  l = cand[i][0]
  r = cand[i][-1]
  temp = min(abs(l)+abs(r-l),abs(r)+abs(l-r))
  ans = min(temp,ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, K = list(map(int, input().split(' ')))
l = list(map(int, input().split(' ')))
minuss = []
pluss = []
for i in l:
    if i < 0:
        minuss = [-i] + minuss
    else:
        pluss = pluss + [i]
minuss = [0] + minuss
pluss = [0] + pluss

# minuss から k本、plussからK-k本取る(短い方を折り返すので2倍)
ans = 1e9
for k in range(N):
    if k >= len(minuss) or K - k >= len(pluss):
        continue
    ans = min(ans, min(minuss[k] * 2 + pluss[K-k], minuss[k] + pluss[K-k] * 2))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
ans = float('inf')
for l in range(0, N-K+1):
    for r in range(l+K-1, N):
        ans = min(ans, abs(X[l]) + abs(X[l] - X[r]))
        ans = min(ans, abs(X[r]) + abs(X[l] - X[r]))
print(ans)

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations

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

print(min([min(abs(cmb[0]) + abs(cmb[-1]-cmb[0]), abs(cmb[-1]) + abs(cmb[0]-cmb[-1])) for cmb in combinations(X,K)]))

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations

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

ans = float('inf')
for cmb in combinations(X,K):
  tmp_ans = min(abs(cmb[0]) + abs(cmb[-1]-cmb[0]), abs(cmb[-1]) + abs(cmb[0]-cmb[-1]))
  if ans > tmp_ans: ans = tmp_ans
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

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

ans = float('inf')
for permutation in permutations(X,K):
  tmp_ans = 0
  prv_pos = 0
  for pos in permutation:
    tmp_ans += abs(pos-prv_pos)
    prv_pos = pos
  if ans > tmp_ans:ans = tmp_ans
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, k = na()
xli = na()
li = []
ans = 1000000000
idx = -1
for i in range(n):
    if xli[i] > 0:
        idx = i
        break
if idx == -1:
    print(abs(xli[-k]))
elif idx == 0:
    print(abs(xli[k-1]))
else:
    for i in range(max(idx - k, 0), min(idx+1, n-k+1)):
        t = xli[i:i + k]
        if t[0] * t[-1] < 0:
            ans = min(ans, 2 * abs(t[0]) + abs(t[-1]), abs(t[0]) + 2 * abs(t[-1]))
        else:
            if t[0] <= 0:
                ans = min(ans, abs(t[0]))
            else:
                ans = min(ans, abs(t[-1]))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, k = na()
xli = na()
li = []
ans = 1000000000
for i in range(n - k + 1):
    t = xli[i:i + k]
    if t[0] * t[-1] < 0:
        ans = min(ans, 2 * abs(t[0]) + abs(t[-1]), abs(t[0]) + 2 * abs(t[-1]))
    else:
        if t[0] <= 0:
            ans = min(ans, abs(t[0]))
        else:
            ans = min(ans, abs(t[-1]))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, k = na()
xli = na()
li = []
ans = 1000000000
for i in range(n - k + 1):
    t = xli[i:i + k]
    if t[0] * t[-1] < 0:
        ans = min(ans, 2 * abs(t[0]) + abs(t[-1]), abs(t[0]) + 2 * abs(t[-1]))
    else:
        if t[0] <= 0:
            ans = min(ans, abs(t[0]))
        else:
            ans = min(ans, abs(t[-1]))
print(ans)

Submission status: Time Limit Exceeded

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

n, k = list(map(int, input().split()))
x_list = list(map(int, input().split()))
x_list = sorted(x_list)
min_l = float('inf')

minus_list = [x for x in x_list if x < 0]
plus_index = len(minus_list)
# print('plus_index: {}'.format(plus_index))
# plus_list = [x for x in work_list if x >= 0]

for i, x in enumerate(x_list):
    l = 0
    minus_list = []
    plus_list = []
    if i + k < plus_index:
        # 全部負の数
        minus_list = x_list[i:i+k]
        plus_list = []
    elif i > plus_index:
        # 全部正の数
        plus_list = x_list[i:i+k]
        minus_list = []
    else:
        minus_list = x_list[i:plus_index]
        diff = k - len(minus_list)
        plus_list = x_list[plus_index: plus_index + (k - len(minus_list))]

    # print(minus_list)
    # print(plus_list)

    minus_l = -minus_list[0] if minus_list else 0
    plus_l = plus_list[-1] if plus_list else 0
    # print('{}, {}'.format(minus_l, plus_l))

    if plus_l > minus_l:
        l = minus_l * 2 + plus_l
    else:
        l = plus_l * 2 +  minus_l

    if l < min_l:
        min_l = l

    if i + k > n - 1:
        break

print(min_l)

Submission status: Time Limit Exceeded

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

n, k = list(map(int, input().split()))
x_list = list(map(int, input().split()))
x_list = sorted(x_list)
min_l = float('inf')
# 0の場所は

for i, x in enumerate(x_list):
    l = 0
    work_list = x_list[i:i+k]
    minus_list = [x for x in work_list if x < 0]
    plus_list = [x for x in work_list if x >= 0]

    minus_l = -minus_list[0] if minus_list else 0
    plus_l = plus_list[-1] if plus_list else 0

    if plus_l > minus_l:
        l = minus_l * 2 + plus_l
    else:
        l = plus_l * 2 +  minus_l

    if l < min_l:
        min_l = l

    if i + k > n - 1:
        break

print(min_l)

Submission status: Time Limit Exceeded

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

n, k = list(map(int, input().split()))
x_list = list(map(int, input().split()))
x_list = sorted(x_list)
min_l = float('inf')
# 0の場所は

for i, x in enumerate(x_list):
    l = 0
    work_list = x_list[i:i+k]
    minus_list = [x for x in work_list if x < 0]
    plus_list = [x for x in work_list if x >= 0]

    if not plus_list:
        l = abs(min(minus_list))
    elif not minus_list:
        l = max(plus_list)
    elif max(plus_list) > max(minus_list):
        l = abs(min(minus_list)) * 2 + max(plus_list)
    else:
        l = max(plus_list) * 2 + abs(min(minus_list))

    if l < min_l:
        min_l = l

    if i + k > n - 1:
        break

print(min_l)

Submission status: Time Limit Exceeded

Solution code:
def solve():
    n, k = map(int, input().split())
    xs = list(map(int, input().split()))
    min_dist = 10 ** 9
    for i in range(n - k + 1):
        part = xs[i:i + k]
        length = abs(part[0] - part[-1])
        dist = min(abs(part[0]) + length, abs(part[-1]) + length)
        if dist < min_dist:
            min_dist = dist
    return min_dist


if __name__ == "__main__":
    print(solve())