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:
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]
        dist = min(abs(part[0]) + abs(part[0] - part[-1]), abs(part[-1]) + abs(part[0] - part[-1]))
        if dist < min_dist:
            min_dist = dist
    return min_dist


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

Submission status: Time Limit Exceeded

Solution code:
def solve():
    n, k = map(int, input().split())
    xs = list(map(int, input().split()))
    dists = []
    for i in range(n - k + 1):
        part = xs[i:i + k]
        dist = min(abs(part[0]) + abs(part[0] - part[-1]), abs(part[-1]) + abs(part[0] - part[-1]))
        dists.append(dist)
    return min(dists)


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

Submission status: Time Limit Exceeded

Solution code:

def resolve():
    n, k = list(map(int, input().split()))
    xxx = list(map(int, input().split()))
    ans = float("inf")
    for i in range(n-k+1):
        lll = xxx[i:i+k]
        max_l = lll[-1]
        min_l = lll[0]
        if not min_l <= 0 <= max_l:
            ans = min(ans, max(abs(min_l), abs(max_l)))
        else:
            ans = min(ans, min(abs(min_l), abs(max_l))+abs(max_l-min_l))
    print(ans)
resolve()

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    n, k = list(map(int, input().split()))
    xxx = list(map(int, input().split()))
    ans = float("inf")
    for i in range(n-k+1):
        lll = xxx[i:i+k]
        if not lll[0] <= 0 <= lll[-1]:
            ans = min(ans, max(abs(lll[0]), abs(lll[-1])))
        else:
            ans = min(ans, min(abs(lll[0]), abs(lll[-1]))+abs(lll[-1]-lll[0]))
    print(ans)
resolve()

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
X_all = list(map(int,input().split()))
m = float("inf")
for i in range(N-K+1):
    X = X_all[i:i+K]
    if X[0] > 0:
        d = X[-1]
    elif X[-1] < 0:
        d = -X[0]
    else:
        d = X[-1]-X[0]+min(-X[0],X[-1])
    m = min(m,d)
print(m)

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):
    temp = x[i:i+k]
    dif = temp[-1] - temp[0]
    from_s = min(abs(temp[-1]), abs(temp[0]))

    ans = min(dif + from_s, ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
def calc_score(x_array):
  score = 0
  for i in range(len(x_array)):
    score += x_array[i]
    x_array = x_array - x
  return score

n, k = map(int, input().split())
x_list = np.array(list(map(int, input().split())))
zero_idx = 0
for i, x in enumerate(x_list):
  if x >= 0:
    zero_idx = i
    break
start_idx = max([zero_idx-k, 0])
end_idx = zero_idx
if zero_idx+k > n:
  end_idx = n - k
min_score = 1000000000

for i in range(start_idx, end_idx+1):
  minus_score = calc_score(abs(x_list[i:zero_idx]))
  plus_score = calc_score(abs(x_list[zero_idx:i+k]))
  double = min(minus_score, plus_score)
  score = minus_score + plus_score + double
  if min_score > score:
    min_score = score
    
print(min_score)

Submission status: Time Limit Exceeded

Solution code:
n, k = [ int(v) for v in input().split() ]
coordinate_list = sorted([ int(v) for v in input().split() ]) 

def fire(inlist):
    if inlist[0] * inlist[-1] >= 0:
        r = max(abs(inlist[0]),abs(inlist[-1]))
    else:
        r = abs(inlist[0]) + abs(inlist[-1]) + min(abs(inlist[0]),abs(inlist[-1]))
    return r

ans = 10**14
for i in range(n-k+1):
    
    ans = min(fire(coordinate_list[i:i+k]),ans)
print(ans)

Submission status: Time Limit Exceeded

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

ref = []
for i in range(N-K+1):
    ref.append(X[i:i+K])

List = []
for j in range(N-K+1):
    if X[j]<=0 and X[j+K-1]>=0:
        List.append(X[j+K-1]-X[j]+min(abs(X[j]),X[j+K-1]))
    else:
        List.append(max(abs(X[j]),abs(X[j+K-1])))

print(min(List))

Submission status: Time Limit Exceeded

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

ref = []
for i in range(N-K+1):
    ref.append(X[i:i+K])


List = []
for k in range(len(ref)):
    if ref[k][0]<=0 and ref[k][-1]>=0:
        List.append(ref[k][-1]-ref[k][0]+min(abs(ref[k][-1]),abs(ref[k][0])))
    else:
        List.append(max(abs(ref[k][-1]),abs(ref[k][0])))

print(min(List))

Submission status: Time Limit Exceeded

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

cost=10**13

for i in range(N-K+1):
    x2=x[i:i+K]
    c=x2[-1]-x2[0]+min(abs(x2[0]),abs(x2[-1]))
    cost=min(cost,c)

print(cost)

Submission status: Time Limit Exceeded

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

import bisect

cost=10**13

for i in range(N-K+1):
    x2=x[i:i+K]
    c=min(abs(min(x2[0],0)),max(0,x2[-1]))*2 + max((-1)*x2[0],x2[-1])
    cost=min(cost,c)

print(cost)

Submission status: Time Limit Exceeded

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

import bisect

zp=bisect.bisect_left(x,0)
cost=10**13

for i in range(max(0,zp-K),min(zp+1,N-K+1)):
    x2=x[i:i+K]
    c=min(abs(min(x2[0],0)),max(0,x2[-1]))*2 + max((-1)*x2[0],x2[-1])
    cost=min(cost,c)

print(cost)

Submission status: Time Limit Exceeded

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

import bisect

zp=bisect.bisect_left(x,0)
cost=[]

for i in range(max(0,zp-K),min(zp+1,N-K+1)):
    x2=x[i:i+K]
    c=min(abs(min(x2[0],0)),max(0,x2[-1]))*2 + max((-1)*x2[0],x2[-1])
    cost.append(c)

print(min(cost))

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 = tmp[-1]
    elif (mini < 0 and maxi < 0):
        a = abs(tmp[0])
    if mini < 0 and maxi >= 0:
        a = abs(tmp[0]) + tmp[-1] + min(abs(tmp[0]), tmp[-1])
    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()))

dist = []
for i in range(N-K+1):
    max_pos = 0
    min_neg = 0
    tmp = x[i:i+K]
    pos = []
    neg = []
    pos = [tmp[j] for j in range(K) if tmp[j] >= 0]
    neg = [tmp[j] for j in range(K) if tmp[j] < 0]
    if pos:
        max_pos = max(pos)
    if neg:
        min_neg = abs(min(neg))
    dist.append((max_pos + min_neg + min(max_pos, min_neg)))

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):
    pos_exist = False
    neg_exist = False
    max_pos = 0
    min_neg = 0
    tmp = x[i:i+K]
    pos = []
    neg = []
    for j in range(K):
        if tmp[j] >= 0:
            pos.append(tmp[j])
            pos_exist = True
        else:
            neg.append(tmp[j])
            neg_exist = True
    if pos_exist:
        max_pos = max(pos)
    if neg_exist:
        min_neg = abs(min(neg))
    dist.append((max_pos + min_neg + min(max_pos, min_neg)))

print(min(dist))

Submission status: Time Limit Exceeded

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

mini = 10**9
for i in range(n-k+1):
    ls = x[i:i+k]
    flg1 = abs(ls[0])+abs(ls[0]-ls[k-1])
    flg2 = abs(ls[k-1])+abs(ls[0]-ls[k-1])
    flg = min(flg1,flg2)
    mini = min(flg,mini)
print(mini)

Submission status: Time Limit Exceeded

Solution code:
n,k=list(map(int,input().split()))
candles=list(map(int,input().split()))
rows=[]
minimum=[]
for i in range(n-k+1):
        new=candles[i:i+k]
        l_r=abs(new[0])+abs(new[-1]-new[0])
        r_l=abs(new[-1])+abs(new[-1]-new[0])
        minimum.append(min(l_r,r_l))

print(min(minimum))

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

N, K = [int(x) for x in stdin.readline().rstrip().split()]
A = [int(x) for x in stdin.readline().rstrip().split()]


def solve(count, time, candle):
    if count == K:
        return time
    if len([x for x in candle if x == 0]) > 0:
        return solve(count + 1, time, [x for x in candle if x != 0])
    index = 0
    if candle[len(candle) - 1] < 0:
        last = len(candle) - 1
        return solve(count + 1, time - candle[last], [x - candle[last] for x in candle if x - candle[index] != 0])
    elif candle[0] > 0:
        return solve(count + 1, time + candle[0], [x - candle[0] for x in candle if x - candle[0] != 0])
    else:
        for l in range(len(candle) - 1):
            if (candle[l] < 0) & (candle[l + 1] > 0):
                index = l
        return min(solve(count + 1, time - candle[index], [x - candle[index] for x in candle if x - candle[index] != 0]),
                   solve(count + 1, time + candle[index + 1],
                         [x - candle[index + 1] for x in candle if x - candle[index + 1] != 0]))


print(solve(0, 0, A))

Submission status: Time Limit Exceeded

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

candidate = []
for i in range(N - K + 1):
    tmp = []
    for j in range(i, i + K):
        tmp.append(x[j])
    candidate.append(tmp)

ans = 1000000000
for i in candidate:
    tmp = 0
    #最初の要素がマイナスだとマイナスとプラスの混合の可能性がある
    if i[0] < 0:
        #混合の場合
        if i[-1] > 0:
            #マイナスに最後に行く場合
            if abs(i[0]) > abs(i[-1]):
                tmp += abs(i[-1]) * 2
                tmp += abs(i[0])
            #プラスに最後に行く場合
            else:
                tmp += abs(i[0]) * 2
                tmp += abs(i[-1])
        #混合じゃない
        else:
            tmp += abs(i[0])
    else:
        #単純にすべて足す。
        tmp += i[-1]
    ans = min(ans, tmp)
print(ans)

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

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
 
import bisect
from collections import defaultdict
import sys
sys.setrecursionlimit(int(1e6))
 
N, K = map(int, input().rstrip().split(' '))
X = sorted(list(map(int, input().rstrip().split(' '))))
 
i = bisect.bisect_left(X, 0)
X.insert(i, 0)
 
memo = defaultdict(lambda: defaultdict(lambda: -1))
 
def recursive(current_k, cost, i, left_i, right_i):
    if K == current_k:
        return cost
    if memo[current_k][i] != -1:
        return memo[current_k][i]
       
    left_cost = 1e10 
    if left_i >= 0:
        left_cost = recursive(current_k + 1, cost + X[i] - X[left_i], left_i, left_i - 1, right_i)
        
    right_cost = 1e10
    if right_i <= N:
        right_cost = recursive(current_k + 1, cost + X[right_i] - X[i], right_i, left_i, right_i + 1)
        
    min_cost = min(left_cost, right_cost)
    
    memo[current_k][i] = min_cost
    
    return min_cost
    
print(recursive(0, 0, i, i - 1, i + 1))

Submission status: Time Limit Exceeded

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):
    if len(plist) == 0:
        return 0

    if len(plist) == 1:
        return abs(plist[0])

    if plist[0] >= 0:
        return plist[-1]

    if  plist[-1] <= 0:
        return abs(plist[0])

    right_cost = plist[-1]
    left_cost = abs(plist[0])
    return min(right_cost, left_cost) * 2 + max(right_cost, left_cost)


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

    min_cost = calc_cost(xlist)
    for i in range(n - k):
        min_cost = min(calc_cost(xlist[i:(i+k)]), min_cost)
    print(min_cost)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

INF = 2*(10**8)+1
memo = INF  # メモ化用変数

def solve():
    N, K = list(map(int, input().split(" ")))
    X = [0]
    X.extend(list(map(int, input().split(" "))))
    X.sort()

    # 幅優先探索すればいいんじゃね？

    def dfs(depth, cost, i, Xs):
        global memo
        if depth == K:
            memo = min(cost, memo)
            return cost
        
        if cost >= memo:
            # 探索を打ち切る
            return INF
        
        ret1, ret2 = INF, INF
        if i+1 < len(Xs):
            # 右に移動
            tmpCost = abs(Xs[i] - Xs[i+1])
            tmpXs = copy.deepcopy(Xs)
            del tmpXs[i]
            ret1 = dfs(depth+1, cost+tmpCost, i, tmpXs)
        if i-1 >= 0:
            # 左に移動
            tmpCost = abs(Xs[i] - Xs[i-1])
            tmpXs = copy.deepcopy(Xs)
            del tmpXs[i]
            ret2 = dfs(depth+1, cost+tmpCost, i-1, tmpXs)
        
        return min(ret1, ret2)

    # 0座標のインデックスは？
    for i in range(len(X)):
        if X[i] == 0:
            break
    ans = dfs(0, 0, i, X)
    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N,K = map(int,input().split())
X = list(map(int,input().split()))
ans = 10**9
for i in range(N-K+1):
    #print(X[i:i+K])
    if min(X[i:i+K]) >= 0:
        #print('a')
        ans = min(ans,max(X[i:i+K]))
    elif max(X[i:i+K]) <= 0:
        #print('b')
        ans = min(ans,abs(min(X[i:i+K])))
    else:
        #print('c')
        ans = min(ans,abs(min(X[i:i+K])*2)+max(X[i:i+K]))
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

tmp = [0] * k
ans = float("inf")
for i in range(n-k+1):
  tmp = a[i:i+k]
  if (tmp[0] <= 0 and tmp[-1] <= 0) or (tmp[0] >= 0 and tmp[-1] >= 0):
    cost = max(abs(tmp[0]), abs(tmp[-1])) 
  else:
    cost = min(abs(tmp[0]), abs(tmp[-1]))*2 + max(abs(tmp[0]), abs(tmp[-1]))
    
  if ans > cost:
    ans = cost
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
"""
map(int,input().split())

X = input().split()
x = []
for i in range(0,len(X)):
    x.append(X[i])

"""
N,K = map(int,input().split())
X = input().split()
xPlus = []
xMinus = []
for i in range(0,len(X)):
    r = int(X[i])
    if r >= 0:
        xPlus.append(r)
    else:
        xMinus.append(abs(r))

if len(xMinus) != 0:
    xMinus.sort()

if len(xPlus) == 0:
    print(xMinus[K-1])
elif len(xMinus) == 0:
    print(xPlus[K-1])
else:
    mn = 10**10
    for k in range(0,K+1):
        notK = K-k
        retp = 0
        retm = 0
        for j in range(0,k):
            if j >= len(xPlus):
                break
            retp += xPlus[j]
        for p in range(0,notK):
            if p >= len(xMinus):
                break
            retm += xMinus[p]
        ret = min(retp,retm)*2 + max(retp,retm)
        mn = min(mn,ret)
    print(mn)

Submission status: Time Limit Exceeded

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

if 0 in x:
    K -= 1
    x.remove(0)

Min = -1
for i in x:
    goal = i
    if goal > 0:
        path = [j for j in x if j < goal]
        if len(path) < K-1:
            pass
        else:
            path = path[-K+1:]
            le = min(path)
            dis = abs(0-le)+abs(goal-le)
            if Min == -1:
                Min = dis
            else:
                if dis < Min:
                    Min = dis
    else:
        path = [j for j in x if j > goal]
        if len(path) < K-1:
            pass
        else:
            path = path[:K-1]
            re = max(path)
            dis = abs(0-re)+abs(goal-re)
            if Min == -1:
                Min = dis
            else:
                if dis < Min:
                    Min = dis

if Min == -1:
    Min = 0

print(Min)

Submission status: Time Limit Exceeded

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

INF = 2*(10**8)+1
memo = INF  # メモ化用変数

def solve():
    N, K = list(map(int, input().split(" ")))
    X = [0]
    X.extend(list(map(int, input().split(" "))))
    X.sort()


    def dfs(depth, cost, i, Xs):
        global memo
        if depth == K:
            memo = min(cost, memo)
            return cost
        
        if cost >= memo:
            # 探索を打ち切る
            return INF
        
        ret1, ret2 = INF, INF
        if i+1 < len(Xs):
            # 右に移動
            tmpCost = abs(Xs[i] - Xs[i+1])
            tmpXs = copy.deepcopy(Xs)
            del tmpXs[i]
            ret1 = dfs(depth+1, cost+tmpCost, i, tmpXs)
        if i-1 >= 0:
            # 左に移動
            tmpCost = abs(Xs[i] - Xs[i-1])
            tmpXs = copy.deepcopy(Xs)
            del tmpXs[i]
            ret2 = dfs(depth+1, cost+tmpCost, i-1, tmpXs)
        
        return min(ret1, ret2)

    # 0座標のインデックスは？
    for i in range(len(X)):
        if X[i] == 0:
            break
    ans = dfs(0, 0, i, X)
    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

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

def solve():
    INF = 2*(10**8)+1
    N, K = list(map(int, input().split(" ")))
    X = [0]
    X.extend(list(map(int, input().split(" "))))
    X.sort()
    
    def dfs(depth, i, Xs):
        if depth == K:
            return 0
        
        ret1, ret2 = INF, INF
        Xs2 = copy.deepcopy(Xs)
        if i+1 < len(Xs):
            # 右に移動
            cost = abs(Xs[i] - Xs[i+1])
            del Xs[i]
            ret1 = dfs(depth+1, i, Xs) + cost
        if i-1 >= 0:
            # 左に移動
            cost = abs(Xs2[i] - Xs2[i-1])
            del Xs2[i]
            ret2 = dfs(depth+1, i-1, Xs2) + cost
        
        return min(ret1, ret2)

    # 0座標のインデックスは？
    for i in range(len(X)):
        if X[i] == 0:
            break
    ans = dfs(0, i, X)
    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

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

def solve():
    INF = 10**8+1
    N, K = list(map(int, input().split(" ")))
    X = [0]
    X.extend(list(map(int, input().split(" "))))
    X.sort()
    
    def dfs(depth, i, Xs):
        if depth == K:
            return 0
        
        ret1, ret2 = INF, INF
        if i+1 < len(Xs):
            # 右に移動
            cost = abs(Xs[i] - Xs[i+1])
            tmpXs = copy.deepcopy(Xs)
            del tmpXs[i]
            ret1 = dfs(depth+1, i, tmpXs) + cost
        if i-1 >= 0:
            # 左に移動
            cost = abs(Xs[i] - Xs[i-1])
            tmpXs = copy.deepcopy(Xs)
            del tmpXs[i]
            ret2 = dfs(depth+1, i-1, tmpXs) + cost
        
        return min(ret1, ret2)

    # 0座標のインデックスは？
    for i in range(len(X)):
        if X[i] == 0:
            break
    ans = dfs(0, i, X)
    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
L = list(map(int, input().split()))
ans = 10 ** 9
for i in range(N-K+1):
    for j in range(K):
        if j == 0:
            tmp = abs(L[i+j])
        else:
            tmp += abs(L[i+j] - L[i+j-1])
    if tmp < ans:
        ans = tmp
    for j in range(K-1, -1, -1):
        if j == K - 1:
            tmp = abs(L[i+j])
        else:
            tmp += abs(L[i+j] - L[i+j+1])
    if tmp < ans:
        ans = tmp
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
L = list(map(int, input().split()))
diff = []
for i in range(N-K+1):
    cand= []
    for j in range(K):
        if j == 0:
            tmp = abs(L[i+j])
        else:
            tmp += abs(L[i+j] - L[i+j-1])
    cand.append(tmp)
    tmp = 0
    for j in range(K-1, -1, -1):
        if j == K - 1:
            tmp = abs(L[i+j])
        else:
            tmp += abs(L[i+j] - L[i+j+1])
    cand.append(tmp)
    diff.append(min(cand))
print(min(diff))

Submission status: Time Limit Exceeded

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

dis = 300000000

for i in range(N-K+1):
    y = list(x[i:i+K])

    disl = abs(x[i]) + abs(x[i+K-1]-x[i])
    disr = abs(x[i+K-1]) + abs(x[i+K-1]-x[i])

    dis = min(dis, disl, disr)
#    if (y[0]*y[-1]<0):
#        disy = y[-1]-y[0]+min(abs(y[-1]), abs(y[0]))
#    else:
#        disy = max(abs(y[0]), abs(y[-1]))
#    dis = min(dis, disy)

print(dis)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

dis = 300000000

for i in range(N-K+1):
    y = list(x[i:i+K])
    if (y[0]*y[-1]<0):
        disy = y[-1]-y[0]+min(abs(y[-1]), abs(y[0]))
    else:
        disy = max(abs(y[0]), abs(y[-1]))
    dis = min(dis, disy)

print(dis)

Submission status: Time Limit Exceeded

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

import bisect
from collections import defaultdict
import sys
sys.setrecursionlimit(int(1e6))
 
N, K = map(int, input().rstrip().split(' '))
X = sorted(list(map(int, input().rstrip().split(' '))))

i = bisect.bisect_left(X, 0)
X.insert(i, 0)

memo = defaultdict(lambda: defaultdict(lambda: -1))
 
def recursive(current_k, cost, i, left_i, right_i):
    if K == current_k:
        return cost
    if memo[current_k][i] != -1:
        return memo[current_k][i]
       
    left_cost = 1e10 
    if left_i >= 0:
        left_cost = recursive(current_k + 1, cost + X[i] - X[left_i], left_i, left_i - 1, right_i)
        
    right_cost = 1e10
    if right_i <= N:
        right_cost = recursive(current_k + 1, cost + X[right_i] - X[i], right_i, left_i, right_i + 1)
        
    min_cost = min(left_cost, right_cost)
    
    memo[current_k][i] = min_cost
    
    return min_cost
    
print(recursive(0, 0, i, i - 1, i + 1))

Submission status: Time Limit Exceeded

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

import bisect
 
N, K = map(int, input().rstrip().split(' '))
X = sorted(list(map(int, input().rstrip().split(' '))))

i = bisect.bisect_left(X, 0)
X.insert(i, 0)

memo = [[-1] * (N + 1) for _ in range(K)]
 
def recursive(current_k, cost, i, left_i, right_i):
    if K == current_k:
        return cost
    if memo[current_k][i] != -1:
        return memo[current_k][i]
       
    left_cost = 1e10 
    if left_i >= 0:
        left_cost = recursive(current_k + 1, cost + X[i] - X[left_i], left_i, left_i - 1, right_i)
        
    right_cost = 1e10
    if right_i <= N:
        right_cost = recursive(current_k + 1, cost + X[right_i] - X[i], right_i, left_i, right_i + 1)
        
    min_cost = min(left_cost, right_cost)
    
    memo[current_k][i] = min_cost
    
    return min_cost
    
print(recursive(0, 0, i, i - 1, i + 1))

Submission status: Time Limit Exceeded

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

N, K = map(int, input().rstrip().split(' '))
X = sorted(list(map(int, input().rstrip().split(' '))) + [0])

i = 0
while True:
    if X[i] == 0:
        break
    i += 1

memo = [[-1] * (N + 1) for _ in range(K)]

def recursive(current_k, cost, i, left_i, right_i):
    if K == current_k:
        return cost
    if memo[current_k][i] != -1:
        return memo[current_k][i]
       
    left_cost = 1e10 
    if left_i >= 0:
        left_cost = recursive(current_k + 1, cost + X[i] - X[left_i], left_i, left_i - 1, right_i)
        
    right_cost = 1e10
    if right_i <= N:
        right_cost = recursive(current_k + 1, cost + X[right_i] - X[i], right_i, left_i, right_i + 1)
        
    min_cost = min(left_cost, right_cost)
    
    memo[current_k][i] = min_cost
    
    return min_cost
    
print(recursive(0, 0, i, i - 1, i + 1))

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
b = []
for i in range(n-k+1):
    temp = a[i:i+k]
    l = temp[0]
    r = temp[-1]
    dist_l = abs(l) + abs(l-r)
    dist_r = abs(r) + abs(l-r)
    dist = min(dist_l, dist_r)
    b.append(dist)
print(min(b))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N , K = map( int , input().split())
lst = list(map(int, input().split()))
ans = 10 ** 9

def getNearestValue(list, num):
    """
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """
    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

nearzero = getNearestValue(lst, 0)
start = max(0 , nearzero- K -1)  
end = min(N - K + 1 , nearzero +  K + 1)
for i in range(start , end):
    # Ｋ個のサブリストを作成する
    lst2 = lst[i: i+K]
    # 全て正（先頭がゼロ以上）であれば、最大の正数（一番右の数）が最小時間となる
    if lst2[0] >= 0:
        ans = min(ans, lst2[-1])
    # 全て負（一番右がゼロ以下）であれば、最小の整数（一番左の数）が最小時間となる
    elif lst2[-1] <= 0:
        ans = min(ans, abs(lst2[0]))
    # 上記以外は、正負混在のケース    
    else:
        #  一番右の方が大きいとき
        if abs(lst2[0]) < lst2[-1]:
            # 負の方向から折り返してくる方が最小なので
            ans = min(ans , abs(lst2[0]) * 2 + lst2[-1])
        else:
            # 正の方向から折り返してくる方が最小なので
            ans = min(ans , abs(lst2[0]) + lst2[-1] * 2)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N , K = map( int , input().split())
lst = list(map(int, input().split()))
ans = 10 ** 9
for i in range(N - K + 1):
    # Ｋ個のサブリストを作成する
    lst2 = lst[i: i+K]
    # 全て正（先頭がゼロ以上）であれば、最大の正数（一番右の数）が最小時間となる
    if lst2[0] >= 0:
        ans = min(ans, lst2[-1])
    # 全て負（一番右がゼロ以下）であれば、最小の整数（一番左の数）が最小時間となる
    elif lst2[-1] <= 0:
        ans = min(ans, abs(lst2[0]))
    # 上記以外は、正負混在のケース    
    else:
        #  一番右の方が大きいとき
        if abs(lst2[0]) < lst2[-1]:
            # 負の方向から折り返してくる方が最小なので
            ans = min(ans , abs(lst2[0]) * 2 + lst2[-1])
        else:
            # 正の方向から折り返してくる方が最小なので
            ans = min(ans , abs(lst2[0]) + lst2[-1] * 2)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

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

if 0 in X:
  K=K-1
ans=[]
Right=[]
Left=[]
  
for x in X:
  if x>0:
    Right.append(x)
  else:
    Left=[abs(x)]+Left

Right=[0]+Right
Left=[0]+Left
    
for i in range(K+1):
  if i<=len(Right)-1 and K-i<=len(Left)-1:
    ans.append(min(Right[i],Left[K-i])*2+max(Right[i],Left[K-i]))

if K==0:
  ans.append(0)

print(min(ans))