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:
#!/usr/bin/env python3
import sys


def solve(N: int, K: int, x: "List[int]"):
    def search_naive(cur, k, x):
        if k == K:
            return 0
        costs = []
        for i in range(len(x)):
            xi = x[i]
            dist = abs(xi-cur)
            costs.append(dist + search_naive(xi, k+1, x[:i]+x[i+1:]))
        return min(costs)
    def search(N, window_size, x):
        costs = []
        for i in range(N-window_size+1):
            conds = x[i:i+window_size]
            right_end = max(filter(lambda x: x>=0, conds), default=0)
            left_end = abs(min(filter(lambda x: x<0, conds), default=0))
            if right_end > left_end:
                costs.append(right_end + 2*left_end)
            else:
                costs.append(2*right_end + left_end)
        return min(costs)
    #print(search_naive(0, 0, x)) 
    print(search(N, K, x))
    return


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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def solve(N: int, K: int, x: "List[int]"):
    def search_naive(cur, k, x):
        if k == K:
            return 0
        costs = []
        for i in range(len(x)):
            xi = x[i]
            dist = abs(xi-cur)
            costs.append(dist + search_naive(xi, k+1, x[:i]+x[i+1:]))
        return min(costs)
    print(search_naive(0, 0, x)) 
    return


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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    global N, K, results
    global right_items, left_items, start_point
    results = []
    N, K = LI()
    X = LI()

    if K == 1 and X == [0]:
        print(0)
        return

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

    if min(X) > 0:
        # 右側しか見ない
        print(max(X[:K]))
        return

    if max(X) < 0:
        # 左側しかみない
        print(abs(min(X[-K:])))
        return

    left_part = []
    right_part = []
    for i in X:
        if i < 0:
            left_part.append(abs(i))
        else:
            right_part.append(i)

    left_part = left_part[::-1][:K]
    right_part = right_part[:K]

    result = 10**8
    for i in range(0, K):
        #  left = d(left_part[:i], 0, 0)
        if len(left_part[:i]) + len(right_part[:K-i]) != K:
            continue
        if len(left_part[:i]) == 0:
            left_distance = 0
        else:
            left_distance = left_part[:i][-1]
        #  right = d(right_part[:K-i], 0, 0)
        if len(right_part[:K-i]) == 0:
            right_distance = 0
        else:
            right_distance = right_part[:K-i][-1]
        #  print('i, left, right', i, left, right)
        #  print('i, left, right', i, left_distance, right_distance)
        #  first = min(left, right)
        #  second = max(left, right)
        first = min(left_distance, right_distance)
        second = max(left_distance, right_distance)
        #  result = min(result, first*2+second)
        result = min(result, first*2+second)

    print(result)


#  def d(arr, s, current_idx):
#      if len(arr) == 0:
#          return 0
#      if len(arr) == 1:
#          return arr[0]

#      print(arr, s)

#      if current_idx == 0:
#          s += arr[0]
#          return d(arr, s, current_idx + 1)

#      if current_idx == len(arr) - 1:
#          return s + arr[current_idx] - arr[current_idx - 1]

#      s += arr[current_idx] - arr[current_idx - 1]
#      return d(arr, s, current_idx + 1)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

min_cost = float('inf')

for i in range(N-K+1):
    sub_x = X[i:i+K]
    tmp_l = abs(sub_x[0]) + abs(sub_x[-1]-sub_x[0])
    tmp_r = abs(sub_x[-1]) + abs(sub_x[0]-sub_x[-1])
    tmp = min(tmp_l,tmp_r)

    if min_cost > tmp:
        min_cost = tmp

print(min_cost)

Submission status: Time Limit Exceeded

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

X_sub = [[] for i in range(N-K+1)]

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

min_cost = float('inf')

for i in X_sub:
    tmp_l = abs(i[0]) + abs(i[-1]-i[0])
    tmp_r = abs(i[-1]) + abs(i[0]-i[-1])
    tmp = min(tmp_l,tmp_r)

    if min_cost > tmp:
        min_cost = tmp

print(min_cost)

Submission status: Time Limit Exceeded

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

X_sub = []

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

min_cost = float('inf')

for i in X_sub:
    tmp_l = abs(i[0]) + abs(i[-1]-i[0])
    tmp_r = abs(i[-1]) + abs(i[0]-i[-1])
    tmp = min(tmp_l,tmp_r)

    if min_cost > tmp:
        min_cost = tmp

print(min_cost)

Submission status: Time Limit Exceeded

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    global N, K, results
    results = []
    N, K = LI()
    X = LI()
    # すべて正にする
    if N == 1 and K == 1 and X == [0]:
        print(0)
        return
    min_x = min(X)
    if min_x < 0:
        X = [x - min_x for x in X]
        # 貪欲的にいく？
        dfs(-min_x, 0, X, 0, 0)
    else:
        dfs(0, 0, X, 0, 0)

    print(min(results))


def dfs(p, s, rest, pidx, count):
    global N, K, results
    # 該当のものを使うか
    # 右に行くか左に行くかの判断
    # k個選んだら終了
    if count == K:
        results.append(s)
        return

    if rest[-1] < p:
        # 右側には数字がない
        dfs(rest[-1], s+p-rest[-1], rest[:-1], 0, count+1)
        return

    if rest[0] > p:
        # 左側に数字がない
        # K個選んで終わり
        dfs(rest[0], s+rest[0] - p, rest[1:], 0, count+1)
        return

    if pidx == 0:
        for ridx, r in enumerate(rest):
            if r > p:
                left = rest[ridx - 1]
                new_rest = rest[:ridx-1] + rest[ridx:]
                dfs(left, s + p - left, new_rest, ridx - 1, count+1)

                right = r
                new_rest = rest[:ridx] + rest[ridx+1:]
                dfs(right, s + right - p, new_rest, ridx, count+1)
                return
    else:
        left = rest[pidx - 1]
        new_rest = rest[:pidx-1] + rest[pidx:]
        dfs(left, s+p-left, new_rest, pidx - 1, count+1)

        right = rest[pidx]
        new_rest = rest[:pidx] + rest[pidx+1:]
        dfs(right, s+right - p, new_rest, pidx, count+1)



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    global N, K, results
    results = []
    N, K = LI()
    X = LI()
    # すべて正にする
    if N == 1 and K == 1 and X == [0]:
        print(0)
        return
    min_x = min(X)
    if min_x < 0:
        X = [x - min_x for x in X]
        # 貪欲的にいく？
        dfs(-min_x, 0, X, 0)
    else:
        dfs(0, 0, X, 0)

    print(min(results))


def dfs(p, s, rest, pidx):
    global N, K, results
    # 該当のものを使うか
    # 右に行くか左に行くかの判断
    # k個選んだら終了
    if len(rest) == N - K:
        results.append(s)
        return

    if rest[-1] < p:
        # 右側には数字がない
        dfs(rest[-1], s+p-rest[-1], rest[:-1], 0)
        return

    if rest[0] > p:
        # 左側に数字がない
        dfs(rest[0], s+rest[0] - p, rest[1:], 0)
        return

    if pidx == 0:
        for ridx, r in enumerate(rest):
            if r > p:
                left = rest[ridx - 1]
                new_rest = rest[:ridx-1] + rest[ridx:]
                dfs(left, s + p - left, new_rest, ridx - 1)

                right = r
                new_rest = rest[:ridx] + rest[ridx+1:]
                dfs(right, s + right - p, new_rest, ridx)
                return
    else:
        left = rest[pidx - 1]
        new_rest = rest[:pidx-1] + rest[pidx:]
        dfs(left, s+p-left, new_rest, pidx - 1)

        right = rest[pidx]
        new_rest = rest[:pidx] + rest[pidx+1:]
        dfs(right, s+right - p, new_rest, pidx)



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    global N, K, results
    results = []
    N, K = LI()
    X = LI()
    # すべて正にする
    if N == 1 and K == 1 and X == [0]:
        print(0)
        return
    min_x = min(X)
    if min_x < 0:
        X = [x - min_x for x in X]
        # 貪欲的にいく？
        dfs(-min_x, 0, X)
    else:
        dfs(0, 0, X)

    print(min(results))


def dfs(p, s, rest):
    global N, K, results
    # 該当のものを使うか
    # 右に行くか左に行くかの判断
    # k個選んだら終了
    if len(rest) == N - K:
        results.append(s)
        return

    if rest[-1] < p:
        # 右側には数字がない
        dfs(rest[-1], s+p-rest[-1], rest[:-1])
        return

    if rest[0] > p:
        # 左側に数字がない
        dfs(rest[0], s+rest[0] - p, rest[1:])
        return

    for ridx, r in enumerate(rest):
        if r > p:
            left = rest[ridx - 1]
            new_rest = rest[:ridx-1] + rest[ridx:]
            dfs(left, s + p - left, new_rest)

            right = r
            new_rest = rest[:ridx] + rest[ridx+1:]
            dfs(right, s + right - p, new_rest)
            break



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    global N, K, results
    results = []
    N, K = LI()
    X = LI()
    # すべて正にする
    if N == 1 and K == 1 and X == [0]:
        print(0)
        return
    min_x = min(X)
    if min_x < 0:
        X = [x - min_x for x in X]
        # 貪欲的にいく？
        dfs(-min_x, 0, X)
    else:
        dfs(0, 0, X)

    print(min(results))


def dfs(p, s, rest):
    global N, K, results
    # 該当のものを使うか
    # 右に行くか左に行くかの判断
    # k個選んだら終了
    if len(rest) == N - K:
        results.append(s)
        return

    if rest[-1] < p:
        # 右側には数字がない
        new_rest = [i - rest[-1] for i in rest]
        dfs(rest[-1], s+p-rest[-1], new_rest[:-1])
    for ridx, r in enumerate(rest):
        if r > p:
            left = rest[ridx - 1]
            new_rest = rest[:ridx-1] + rest[ridx:]
            dfs(left, s + p - left, new_rest)

            right = r
            new_rest = rest[:ridx] + rest[ridx+1:]
            dfs(right, s + right - p, new_rest)
            break



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N, K   = map(int, input().split())
L = list(map(int, input().split()))
L.append(0)
L=sorted(L)
dis = []
for i in range(N-K+1):
    if 0 in L[i:i+K+1]:
        l = L[i:i+K+1]
              
        d = abs(l[0]) + abs(l[-1])*2
        dis.append(d)
        d = abs(l[0])*2 + abs(l[-1])
        dis.append(d)
print(min(dis))

Submission status: Time Limit Exceeded

Solution code:
N, K   = map(int, input().split())
L = list(map(int, input().split()))
L.append(0)
L.sort()
dis = []
for i in range(N-K+1):
    if 0 in L[i:i+K+1]:
        l = L[i:i+K+1]
              
        d = abs(l[0]) + abs(l[-1])*2
        dis.append(d)
        d = abs(l[0])*2 + abs(l[-1])
        dis.append(d)
print(min(dis))

Submission status: Time Limit Exceeded

Solution code:
def solve(N, K, Xs):
    plus = sorted([x for x in Xs if x >= 0])
    minus = sorted([abs(x) for x in Xs if x < 0])
    ans = 10 ** 9
    for i in range(0, max(K, len(plus)) + 1):
        ps = plus[:i]
        ms = minus[:K - i]
        if len(ps) == K:
            ans = min(ans, ps[-1])
            continue
        if len(ms) == K:
            ans = min(ans, ms[-1])
            continue
        if len(ps) + len(ms) == K:
            p, m = ps[-1], ms[-1]
            ans = min(ans, p * 2 + m, m * 2 + p)

    return ans
  
if __name__ == "__main__":
    N, K = tuple(map(int, input().split(" ")))
    Xs = list(map(int, input().split(" ")))
    print(solve(N, K, Xs))

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
lis=list(map(int,input().split()))
result=10**9
for i in range(K,N+1):
    if i!=N and lis[i]<0:
        continue
    elif i-K>0 and lis[i-K-1]>0:
        break
    else:
        t=lis[i-K:i]
        if t[0]*t[-1]>=0:
            res=max(abs(t[0]),abs(t[-1]))
            result=min(result,res)
        else:
            x0=abs(t[0])
            x1=abs(t[-1])
            result=min(result,2*x0+x1,x0+2*x1)
print(result)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
lis=[int(i) for i in input().split()]
result=[]
for i in range(K,N+1):
    if i!=N and lis[i]<0:
        continue
    elif i-K>0 and lis[i-K-1]>0:
        break
    else:
        t=lis[i-K:i]
        if t[0]*t[-1]>=0:
            res=max(abs(t[0]),abs(t[-1]))
            result.append(res)
        else:
            x0=abs(t[0])
            x1=abs(t[-1])
            res=min(2*x0+x1,x0+2*x1)
            result.append(res)
print(min(result))

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
lis=[int(i) for i in input().split()]
result=[]
for i in range(K,N+1):
    t=lis[i-K:i]
    if t[0]*t[-1]>=0:
        res=max(abs(t[0]),abs(t[-1]))
        result.append(res)
    else:
        x0=abs(t[0])
        x1=abs(t[-1])
        res=min(2*x0+x1,x0+2*x1)
        result.append(res)
print(min(result))

Submission status: Time Limit Exceeded

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

ans = 10**18
for i in range(N-K+1):
    y = x[i:i+K]
    y0 = x[i]
    yk = x[i+K-1]
    if yk < 0:
        ans = min(ans, abs(y0))
    elif y0 <= 0 and 0 <= yk:
        ans = min(ans, yk-2*y0, 2*yk-y0)
    else:
        ans = min(ans, yk)

print(ans)

Submission status: Time Limit Exceeded

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

ans = 10**18
for i in range(N-K+1):
    y = x[i:i+K]
    if y[0] < 0 and y[K-1] < 0:
        ans = min(ans, abs(y[0]))
    elif y[0] <= 0 and 0 <= y[K-1]:
        ans = min(ans, y[K-1]-2*y[0], 2*y[K-1]-y[0])
    else:
        ans = min(ans, y[K-1])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
b = list(map(int, input().split()))
a = list(map(int, input().split()))

p = [i for i in a if i > 0]
m = [i for i in a if i <= 0]
p = np.append(np.diff(np.append([0],p)),[10**10])
m = np.abs(np.append([10**10],np.diff(np.append(m,[0]))))

lp = [0]
lm = [0]

for i in range(b[1]):
    if p[0] > m[-1]:
        lm = lm + m[-1]
        m = np.delete(m, -1)
    else:
        lp = lp + p[0]
        p = np.delete(p, 0)

res = int(lp + lm + min(lm,lp))

print(res)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
b = list(map(int, input().split()))
a = list(map(int, input().split()))

p = np.append(np.diff(np.sort([i for i in a if i > 0] + [0])),[10**10])
m = np.append(np.diff(np.sort(np.abs([i for i in a if i <= 0] + [0]))),[10**10])

lp = []
lm = []
for i in range(b[1]):
    if p[0] > m[0]:
        lm.append(m[0])
        m = np.delete(m, 0)
    else:
        lp.append(p[0])
        p = np.delete(p, 0)

res = sum(lp) + sum(lm) + min(sum(lp),sum(lm))

print(res)

Submission status: Time Limit Exceeded

Solution code:
a,b = map(int,input().split(" "))
ar = list(map(int,input().split(" ")))
br = []
for i in range(a-b+1):
    l = ar[i:i+b]
    br.append(min(abs(l[0]-l[b-1])+abs(l[0]),abs(l[0]-l[b-1])+abs(l[b-1])))
print(min(br))

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
else:
    x.append(0)
    x.sort()

time=[]
def measureTime(i,regX,nowTime,nowPlace,direct,turnFlg):
    if i<k:
        if len(regX)>1:
            newRegX=regX[:]
            newRegX.pop(nowPlace)
            if (nowPlace>0) & ((direct==0)|(turnFlg!=1)):
                newTimeM=nowTime+abs(regX[nowPlace]-regX[nowPlace-1])
                # print('{},place={},time={}'.format(newRegX,nowPlace-1,newTimeM))
                if direct==1:
                    turnFlg=1
                measureTime(i+1, newRegX, newTimeM, nowPlace-1, 0, turnFlg)
            if (nowPlace<len(regX)-1) & ((direct==1)|(turnFlg!=1)):
                newTimeP=nowTime+abs(regX[nowPlace]-regX[nowPlace+1])
                # print('{},place={},time={}'.format(newRegX,nowPlace,newTimeP))
                if direct==0:
                    turnFlg=1
                measureTime(i+1, newRegX, newTimeP, nowPlace, 1, turnFlg)
        else:
            if i==k:
                time.append(nowTime)
    else:
        time.append(nowTime)

measureTime(0,x,0,x.index(0),-1,0)
time.sort()
print(time[0])

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
else:
    x.append(0)
    x.sort()
place=x.index(0)
time=[]
def measureTime(i,regX,nowTime,nowPlace):
    if i<k:
        if len(regX)<=1:
            time.append(nowTime)
        else:
            newRegX=regX[:]
            newRegX.pop(nowPlace)
            if nowPlace>0:
                newTimeM=nowTime+abs(regX[nowPlace]-regX[nowPlace-1])
                # print('{},place={},time={}'.format(newRegX,nowPlace-1,newTimeM))
                measureTime(i+1, newRegX, newTimeM, nowPlace-1)
            if nowPlace<len(regX)-1:
                newTimeP=nowTime+abs(regX[nowPlace]-regX[nowPlace+1])
                # print('{},place={},time={}'.format(newRegX,nowPlace,newTimeP))
                measureTime(i+1, newRegX, newTimeP, nowPlace)
    else:
        time.append(nowTime)

measureTime(0,x,0,place)
time.sort()
print(time[0])

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
x=[int(i) for i in input().split()]
l,r=[],[]
for i in range(n):
    if x[i]<0 and i+1<n: l.append(abs(x[i]-min(x[i+1],0)))
    elif x[i]<0: l.append(-x[i])
    if x[i]>=0 and i>0: r.append(x[i]-max(0,x[i-1]))
    elif x[i]>=0: r.append(x[i])

l=l[::-1]
l=l[:k]
r=r[:k]
ll=len(l)
rr=len(r)

ans=sum(l)*2+sum(r)*2
for i in range(ll):
    if k-1==i: ans=min(ans,sum(l))
    elif i+rr+1>=k: ans=min(ans,sum(l[:i+1])*2+sum(r[:k-i-1]))

for i in range(rr):
    if k-1==i: ans=min(ans,sum(r))
    elif i+ll+1>=k: ans=min(ans,sum(r[:i+1])*2+sum(l[:k-i-1]))
print(ans)

Submission status: Time Limit Exceeded

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

for i in range(n - k + 1):
    x_k = x[i:i+k]
    #print(x_k)
    
    if x_k[0] >= 0:
        t = x_k[-1]
            
    elif x_k[-1] <= 0:
        t = -x_k[0]
    
    else:
        t = min(-x_k[0] + x_k[-1] *2,-x_k[0] * 2 + x_k[-1])

    time = min(t, time)
    
print(time)

Submission status: Time Limit Exceeded

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

for i in range(n - k + 1):
    x_k = x[i:i+k]
    #print(x_k)
    
    if x_k[0] >= 0:
        t = x_k[-1]
            
    elif x_k[-1] <= 0:
        t = -x_k[0]
    
    elif -x_k[0] <= x_k[-1]:
        t = -x_k[0] * 2 + x_k[-1]
    
    else:
        t = -x_k[0] + x_k[-1] *2

    time = min(t, time)
    
print(time)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
x = list(map(int,input().split()))
if K==1 and (0 in x):
    print(0)
else:
    if 0 in x:
        pass
    else:
        K += 1
        counter = 0
        for i in x:
            if i > 0:
                break
            else:
                counter += 1
        x.insert(counter,0)

    result = 10000000000000000000
    g,s = x.index(0),x.index(0)-K+1
    while (not s>x.index(0)):
        if s<0 or g>(len(x)-1):
            s += 1
            g += 1
            continue
        else:
            ad_1 = 2*(-x[s]) + x[g]
            ad_2 = -x[s] + 2*(x[g])
            result = min(ad_1,ad_2,result)
            s += 1
            g += 1
    print(result)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
x = list(map(int,input().split()))
if K==1 and (0 in x):
    print(0)
else:
    if 0 in x:
        pass
    else:
        K += 1
        counter = 0
        for i in x:
            if i > 0:
                break
            else:
                counter += 1
        x.insert(counter,0)

    result = 10000000000000000000
    g,s = x.index(0),x.index(0)-K+1
    while (not s>x.index(0)):
        if s<0 or g>(len(x)-1):
            s += 1
            g += 1
            continue
        else:
            ad_1 = 2*(abs(x[s])) + abs(x[g])
            ad_2 = abs(x[s]) + 2*(abs(x[g]))
            result = min(ad_1,ad_2,result)
            s += 1
            g += 1
    print(result)

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,input().split())
x=list(map(int,input().split()))
mlist=[]
for i in range(N-K+1):
    c=x[i:K+i]
    cr,cl=[x for x in c if x >= 0],[-x for x in c if x < 0]
    if cr==[]:
        m=max(cl)
    elif cl==[]:
        m=max(cr)
    else:
        r,l=max(cr),max(cl)
        m=min(r,l)+r+l
    mlist.append(m)
print(min(mlist))

Submission status: Time Limit Exceeded

Solution code:
N,K=(int(i) for i in input().split(' '))
x=[int(i) for i in input().split(' ')]
time=None
minus=[]
plus=[]
for i in range(len(x)):
  if x[i]==0:
    K-=1
  elif x[i]<0:
    minus=[-x[i]]+minus
  elif x[i]>0:
    plus=plus+[x[i]]
for i in range(len(minus)):
  minus=list(minus)
  minus[i]=-minus[i]
  minus=list(reversed(minus))
minus=[0]+minus
plus=[0]+plus
for i in range(max(K-len(plus)+1,0),min(K+1,len(minus))):
  if minus[i]>plus[K-i]:
    time_tmp=minus[i]+2*plus[K-i]
  else:
    time_tmp=2*minus[i]+plus[K-i]
  if time==None:
    time=time_tmp
  if time_tmp<time:
    time=time_tmp
print(time)

Submission status: Time Limit Exceeded

Solution code:
import copy
 
n,k = map(int,input().split())
x = list(map(int,input().split()))
 
blist = []
for i in range(2**(k)):
    blist.append(list(map(int,list(bin(i)[2::].zfill(k)))))
 
if 0 in x:
    x.remove(0)
    k -= 1
 
ans = 10**14
for blis in blist:
    s = 0
    xs = copy.deepcopy(x)
    aans = 0
    for bli in blis:
        if bli == 1:
            for i in range(len(xs)):
                if xs[i] > s:
                    s1 = xs.pop(i)
                    aans += abs(s-s1)
                    s = s1
                    break
                if i == len(xs)-1:
                    s1 = xs.pop(i-1)
                    aans += abs(s-s1)
                    s = s1
                    break
        else:
            for i in range(len(xs))[::-1]:
                if xs[i] < s:
                    s1 = xs.pop(i)
                    aans += abs(s-s1)
                    s = s1
                    break
                if i == 0:
                    s1 = xs.pop(1)
                    aans += abs(s-s1)
                    s = s1
                    break
        if aans >= ans:
            break 
    ans = min(ans,aans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import copy

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

blist = []
for i in range(2**(k)):
    blist.append(list(map(int,list(bin(i)[2::].zfill(k)))))

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

ans = 10**14
for blis in blist:
    s = 0
    xs = copy.deepcopy(x)
    aans = 0
    for bli in blis:
        if bli == 1:
            for i in range(len(xs)):
                if xs[i] > s:
                    s1 = xs.pop(i)
                    aans += abs(s-s1)
                    s = s1
                    break
                if i == len(xs)-1:
                    s1 = xs.pop(i-1)
                    aans += abs(s-s1)
                    s = s1
                    break
        else:
            for i in range(len(xs))[::-1]:
                if xs[i] < s:
                    s1 = xs.pop(i)
                    aans += abs(s-s1)
                    s = s1
                    break
                if i == 0:
                    s1 = xs.pop(1)
                    aans += abs(s-s1)
                    s = s1
                    break
    ans = min(ans,aans)
print(ans)

Submission status: Time Limit Exceeded

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

for i in range(N-K+1):
	length=0
	for j in range(K-1):
		length+=abs(x[i+j+1]-x[i+j])
	cost.append(length+abs(x[i]))
	cost.append(length+abs(x[i+K-1]))
print(min(cost))

Submission status: Time Limit Exceeded

Solution code:
N, K = list(map(int, input().split()))
candles = list(map(int, input().split()))
abs_c = [abs(c) for c in candles]
result = []
for n in range(N-K+1):
    route = candles[n:n+K]
    r1 = abs(route[0]) + abs(route[-1]-route[0])
    r2 = abs(route[-1]) + abs(route[0]-route[-1])
    result.append(min(r1, r2))

print(min(result))

Submission status: Time Limit Exceeded

Solution code:
N, K = list(map(int, input().split()))
candles = list(map(int, input().split()))
abs_c = [abs(c) for c in candles]
result = []
for n in range(N-K+1):
    result.append(sum(abs_c[n:n+K]))

idx = result.index(min(result))
route = candles[idx:idx+K]

r1 = abs(route[0]) + abs(route[-1]-route[0])
r2 = abs(route[-1]) + abs(route[0]-route[-1])
print(min(r1, r2))

Submission status: Time Limit Exceeded

Solution code:
def binarySearch(list_a, key):
    left = 0
    right = len(list_a)
    while left < right:
        mid = (left + right) // 2
        if list_a[mid] == key:
            return mid
            break
        elif key < list_a[mid]:
            right = mid
        else:
            left = mid+1
    else:
        return mid

n,k = map(int, input().split())
list_x = list((map(int, input().split())))
ans = 10**9
key_point = binarySearch(list_x,0)
for i in range(key_point-k+1,key_point+1):
    if i < 0:
        continue
    try:
        prob_list = list_x[i:i+k]
        dist = min(abs(prob_list[0]),abs(prob_list[k-1])) + (prob_list[k-1] - prob_list[0])
        if ans > dist:
            ans = dist
    except:
        pass
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int, input().split())
list_x = list((map(int, input().split())))
ans = 10**9
for i in range(0,n-k+1):
    prob_list = list_x[i:i+k]
    dist = min(abs(list_x[i]),abs(list_x[i+k-1])) + (list_x[i+k-1] - list_x[i])
    if ans > dist:
        ans = dist
print(ans)