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: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
from bisect import bisect, bisect_left
def inpl(): return list(map(int, input().split()))
N, K = inpl()
X = inpl()
ans = 10**9

r0 = bisect_left(X, 0)

for i in range(N):
   # print(r0+i, r0-K+i+1)
    if (0 <= r0+i < N) and (0 <= r0-K+i+1 < N):
        if X[r0+i] < 0 or X[r0-K+i+1] > 0:
            continue
        #print(2*X[r0+i] - X[r0-K+i+1])
        #print(X[r0+i] - 2*X[r0-K+i+1])
        ans = min(ans, 2*X[r0+i] - X[r0-K+i+1])
        ans = min(ans, X[r0+i] - 2*X[r0-K+i+1])

if r0+K < N:
    ans = min(X[r0+K-1], ans)
if r0-K > N:
    ans = min(X[r0-K+1], ans)

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, K, X):
    xs = [0]
    x0 = X[0]
    for x in X:
        xs.append(xs[-1] + x - x0)

    ans = sys.maxsize
    for i in range(N-K+1):
        c = 0
        if X[i] <= 0 and X[i+K-1] <= 0:
            c += -X[i]
        elif X[i] <= 0 and X[i+K-1] > 0:
            c += -2*X[i] + X[i+K-1]
        else:
            c += X[i+K-1]

        # print(c)
        ans = min(ans, c)
    return ans


def main():
    N, K = read_int_n()
    X = read_int_n()
    print(slv(N, K, X))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

ans = float('inf')

if N == K:
    if x[0] >= 0:
        ans = x[-1]
    elif x[-1] <= 0:
        ans = -x[0]
    else:
        l = -x[0]
        r = x[-1]
        mi = min(l,r)
        mx = max(l,r)
        ans = mi*2+mx

for i in range(N-K+1):
    if x[i] >= 0 and x[i+K-1] >= 0:
        ans = min(ans,x[i+K-1])
    elif x[i] < 0 and x[i+K-1] < 0:
        ans = min(ans,-x[i+K-1])
    else:
        l = -x[i]
        r = x[i+K-1]
        m = min(l,r)
        mx = max(l,r)
        ans = min(ans,m*2+mx)

print(ans)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left
s=input().split()
n,k=int(s[0]),int(s[1])
s=input().split()
l=[int(s[i]) for i in range(n)]
if min(l)>=0:
    print(l[k-1])
elif max(l)<=0:
    print(l[-k])
else:
    ind=bisect_left(l,0)
    if l[ind]==0:
        k-=1
        del(l[ind])
    costr=[0]+l[ind:]
    lef=l[:ind]
    costl=[0]+[-lef[-i] for i in range(1,1+len(lef))]
    if k==0:
        print(0)
    else:
        res=10000000000000000000
        for i in range(len(costr)):
            if i>k:
                break
            nowcost=costr[i]*2
            if k-i<len(costl):
                res=min(res,nowcost+costl[k-i])
        for i in range(len(costl)):
            if i>k:
                break
            nowcost=costl[i]*2
            if k-i<len(costr):
                res=min(res,nowcost+costr[k-i])
        print(res)

Submission status: Wrong Answer

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

l1 = []
l2 = []
for i in range(N):
    if x[i] == 0:
        K -= 1
    elif x[i] > 0:
        l1.append(x[i])
    else:
        l2.append(-x[i])

l2.sort()

ans = 10**9
if K == 0:
    ans = 0
else:
    if K <= len(l1):
        ans = min(ans, l1[K-1])
    if K <= len(l2):
        ans = min(ans, l2[K-1])

for i in range(max(1, K-len(l1)), min(K, len(l2)+1)):
    ans = min(ans, l1[K-1-i]+l2[i-1]*2, l1[K-1-i]+l2[i-1]*2)

print(ans)

Submission status: Wrong Answer

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

ans = float('inf')

if N == K:
    if x[0] >= 0:
        ans = x[-1]
    elif x[-1] <= 0:
        ans = -x[0]
    else:
        l = x[0]
        r = x[-1]
        mi = min(l,r)
        mx = max(l,r)
        ans = mi*2+mx

for i in range(N-K+1):
    if x[i] >= 0 and x[i+K-1] >= 0:
        ans = min(ans,x[i+K-1])
    elif x[i] < 0 and x[i+K-1] < 0:
        ans = min(ans,-x[i+K-1])
    else:
        l = -x[i]
        r = x[i+K-1]
        m = min(l,r)
        mx = max(l,r)
        ans = min(ans,m*2+mx)


print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
a=list(map(int, input().split()))
b=sorted([-1*i for i in a])
ans=10**9
for i in range(n-k+1):
    if a[i]>=0:ans=min(ans,a[k-1])
    else:
        ans=min(ans,a[k+i-1]-a[i]*2)
for i in range(n-k+1):
    if b[i]>=0:ans=min(ans,a[k-1])
    else:
        ans=min(ans,b[k+i-1]-b[i]*2) 
print(ans)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left

n, k = map(int, input().split())
x = list(map(int, input().split()))
pos = bisect_left(x, 0)
#print(bisect_left(x, 0))

if x[0] >= 0:
	print(x[k - 1])
elif x[-1] <= 0:
	print(-x[-k])
else:
	ans = float("inf")
	if pos + k <= n:
		ans = x[pos + k - 1]
	if x[pos] == 0:
		if pos - k - 1 >= 0:
			ans = min(ans, x[pos - k - 1])
	else:
		if pos - k >= 0:
			ans = min(ans, x[pos - k])
	for i in range(max(pos, k - 1 - pos), min(pos + k - 1, n)):
		#print(i)
		right = x[i]
		left = -x[pos - (k - (i - pos + 1))]
		#print(right, left)
		ans = min(ans, 2 * right + left, 2 * left + right)

	print(ans)

Submission status: Wrong Answer

Solution code:
# S = input()
# N = int(input())
N, K = map(int, input().split())
X = list(map(int, input().split()))
# LR = [list(map(int, input().split())) for _ in range(M)]

ans = 10000000000

if K == 1:
    for i in range(N):
        if ans > abs(X[i]):
            ans = abs(X[i])
else:
    for i in range(N - K):
        left = X[i]
        right = X[i + K - 1]
        sum = 0

        if abs(left) <= abs(right):
            sum += abs(left)
        else:
            sum += abs(right)

        sum += abs(left - right)

        if ans > sum:
            ans = sum

print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
X = list(map(int,input().split()))
x_n = sorted([-x for x in X if x < 0])
x_p = sorted([x for x in X if x >= 0])
size_n,size_p = len(x_n), len(x_p)
ans = 2 * 10**8
if size_n >= K:
	ans = min(ans, x_n[K-1])
if size_p >= K:
	ans = min(ans, x_p[K-1])
for i in range(1,K):
	if i <= size_n and K-i <= size_p:
		ans = min(ans, x_n[i-1] + x_p[K-i-1] + min(x_n[i-1], x_p[K-i-1]))
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
X = list(map(int,input().split()))
x_n = sorted([-x for x in X if x < 0])
x_p = sorted([x for x in X if x >= 0])
size_n,size_p = len(x_n), len(x_p)
ans = 2 * 10**8
if size_n >= K:
	ans = min(ans, x_n[K-1])
if size_p >= K:
	ans = min(ans, x_p[K-1])
print(ans)
for i in range(1,K):
	if i <= size_n and K-i <= size_p:
		ans = min(ans, x_n[i-1] + x_p[K-i-1] + min(x_n[i-1], x_p[K-i-1]))
print(ans)

Submission status: Wrong Answer

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

ans = float('inf')

if N == K:
    if x[0] >= 0:
        ans = x[-1]
    elif x[-1] <= 0:
        ans = -x[0]
    else:
        l = x[0]
        r = x[-1]
        mi = min(l,r)
        mx = max(l,r)
        ans = mi*2+mx

for i in range(N-K):
    if x[i] >= 0 and x[i+K-1] >= 0:
        ans = min(ans,x[i+K-1])
    elif x[i] < 0 and x[i+K-1] < 0:
        ans = min(ans,-x[i+K-1])
    else:
        l = -x[i]
        r = x[i+K-1]
        m = min(l,r)
        mx = max(l,r)
        ans = min(ans,m*2+mx)


print(ans)

Submission status: Wrong Answer

Solution code:
import bisect


def solve(n, k, xxx):
    i0 = bisect.bisect(xxx, 0)
    if i0 == 0:
        return xxx[k - 1]
    if i0 == n:
        return -xxx[-k]

    xxx.insert(i0, 0)
    # print(xxx)
    ans = float('inf')
    for p in range(k + 1):
        li = i0 - k + p
        ri = i0 + p
        # print(p, li, ri, -xxx[li] * 2 + xxx[ri], -xxx[li] + xxx[ri] * 2)
        if li < 0 or ri >= n:
            continue
        ans = min(ans, -xxx[li] * 2 + xxx[ri], -xxx[li] + xxx[ri] * 2)
    return ans


n, k = map(int, input().split())
xxx = list(map(int, input().split()))
print(solve(n, k, xxx))

Submission status: Wrong Answer

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

ans = 10 ** 10
for  i,x  in enumerate(xs):
    if i +  K == N:
        break
    if x >= 0 and i > 0:
        break
    num = abs(xs[ i + K - 1 ] - xs[i]) + abs(xs[i])
    if num < ans:
        ans = num
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left

n, k = map(int, input().split())
x = list(map(int, input().split()))
pos = bisect_left(x, 0)
#print(bisect_left(x, 0))

if x[0] >= 0:
	print(x[k - 1])
elif x[-1] <= 0:
	print(-x[-k])
else:
	ans = float("inf")
	for i in range(max(pos, k - 1 - pos), min(pos + k - 1, n)):
		#print(i)
		right = x[i]
		left = -x[pos - (k - (i - pos + 1))]
		#print(right, left)
		ans = min(ans, 2 * right + left, 2 * left + right)

	print(ans)

Submission status: Wrong Answer

Solution code:
import bisect


def solve(n, k, xxx):
    i0 = bisect.bisect(xxx, 0)
    if i0 == 0:
        return xxx[0]
    if i0 == n:
        return -xxx[-1]

    xxx.insert(i0, 0)
    # print(xxx)
    ans = float('inf')
    for p in range(k + 1):
        li = i0 - k + p
        ri = i0 + p
        # print(p, li, ri, -xxx[li] * 2 + xxx[ri], -xxx[li] + xxx[ri] * 2)
        if li < 0 or ri >= n:
            continue
        ans = min(ans, -xxx[li] * 2 + xxx[ri], -xxx[li] + xxx[ri] * 2)
    return ans


n, k = map(int, input().split())
xxx = list(map(int, input().split()))
print(solve(n, k, xxx))

Submission status: Wrong Answer

Solution code:
def main():
    n, k = map(int, raw_input().split(" "))

    data = map(int, raw_input().split(" "))

    from bisect import bisect_left

    l = bisect_left(data, 0)

    if l == 0:
        return data[k - 1]
    if l == n:
        return - data[n - k + 1]


    res = float("inf")
    for i in range(max(1, l + k - n), l+1):
        res = min(res,  - data[l - i] * 2 + data[l + k - i- 1])
        res = min(res, - data[l - i] + 2 * data[l + k - i - 1])
    return res

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

Submission status: Wrong Answer

Solution code:
n, k = tuple(map(int, input().split()))
arr = list(map(int, input().split()))
res = 1000000000
for i in range(n-k+1):
    if arr[i]*arr[i+k-1] < 0:
        res = min([res, -2*arr[i]+arr[i+k-1], 2*arr[i+k-1]-arr[i]])
    elif arr[i+k-1] < 0:
        res = min(res, arr[i]*-2)
    else:
        res = min(res, 2*arr[i+k-1])

print(res)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
X = [int(x) for x in input().split()]
L = []
R = []
for i, x in enumerate(X):
  if x < 0:
    L = [-x] + L
  elif x == 0:
    K -= 1
  else:
    L = [0] + L
    R = [0] + X[i:]
    break
ans = 10 ** 9
for i in range(K):
  if i < len(R) and K - i < len(L):
    ans = min(R[i] * 2 + L[K - i], ans)
  if i < len(L) and K - i < len(R):
    ans = min(L[i] * 2 + R[K - i], ans)
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    n, k = map(int, raw_input().split(" "))

    data = map(int, raw_input().split(" "))

    from bisect import bisect_left

    l = bisect_left(data, 0)

    if l == 0:
        return data[k - 1]
    if l == n:
        return - data[n - k + 1]


    res = float("inf")
    for i in range(max(1, l + k - n), l+1):
        res = min(res,  - data[l - i] * 2 + data[l + k - i- 1])
    return res

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

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
x=[int(i) for i in input().split()]
ans=10**9
A=[]
aaa=[]
for i in range(N):
    if x[i]>=0:
        A.append(x[i])
    else:
        aaa.append(-x[i])
B=aaa[::-1]
C=len(A)
D=len(B)
if C==0:
    print(B[K-1])
    exit()
elif D==0:
    print(A[K-1])
    exit()
for i in range(K+1):
    if i>=C or K-i>=D:
        continue
    tmp1=2*A[i-1]+B[K-i-1]
    tmp2=A[i-1]+2*B[K-i-1]
    ans=min([ans,tmp1,tmp2])
print(ans)

Submission status: Wrong Answer

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

ans = float('inf')
for i in range(N-K):
    if x[i] >= 0 and x[i+K-1] >= 0:
        ans = min(ans,x[i+K-1])
    elif x[i] < 0 and x[i+K-1] < 0:
        ans = min(ans,-x[i+K-1])
    else:
        l = -x[i]
        r = x[i+K-1]
        m = min(l,r)
        mx = max(l,r)
        ans = min(ans,m*2+mx)

if ans == float('inf'):
    ans = 0
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
X = list(map(int,input().split()))
x_n = sorted([-x for x in X if x < 0])
x_p = sorted([x for x in X if x >= 0])
size_n,size_p = len(x_n), len(x_p)
ans = 10**8
if size_n >= K:
	ans = min(ans, x_n[K-1])
if size_p >= K:
	ans = min(ans, x_p[K-1])
for i in range(1,K):
	if i <= size_n and K-i <= size_p:
		ans = min(ans, x_n[i-1] + x_p[K-i-1] + min(x_n[i-1], x_p[K-i-1]))
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
L = [0] + [x for x in X if x < 0][::-1]
R = [0] + [x for x in X if x >= 0]

ans = float("inf")
for i in range(len(L)):
    try:
        ans = min(ans, abs(L[i]) * 2 + R[K-i])
    except:
        pass

print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int, input().split())
a=list(map(int, input().split()))
ans=10**8
if a[0]>0:print(a[k-1])
else:
    for i in range(n-k+1):
        if a[i]>0:ans==a[k-1]
        else:
            ans=min(ans,a[k+i-1]-a[i]*2)
    print(ans)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
x=list(map(int,input().split()))
index = 0
ans = 10**9
while index + K - 1 < N:
    start = x[index]
    end = x[index + K - 1]
    if start < 0:
        ans = min(ans,end - 2*start)
    else:
        ans = min(ans,end)
    index += 1
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
L = [0] + [x for x in X if x < 0][::-1]
R = [0] + [x for x in X if x > 0]

if 0 in X:
    K -= 1

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

ans = float("inf")
for i in range(len(L)):
    try:
        ans = min(ans, abs(L[i]) * 2 + R[K-i])
    except:
        pass

print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
# encoding:utf-8
def main():
	n, k = list(map(int, input().split()))
	xs = list(map(int, input().split()))
	
	min_dist = 10 ** 10
	for i in range(n - k + 1):
		dist = abs(xs[i]) + (xs[i + k - 1] - xs[i])
		if dist <= min_dist:
			min_dist = dist
	print(min_dist)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
from scipy.special import comb
import itertools

n, k = map(int, input().split())
x = list(map(int, input().split()))
X = []
m = 3*10**8

for v in itertools.combinations(x, k):
    X.append(list(v))

for i in range(comb(n, k, exact=True)):
    m0 = min(X[i])
    m1 = max(X[i])
    a = min(abs(m0)+abs(m1-m0), abs(m1)+abs(m1-m0))
    if m > a:
        m = a
print(m)

Submission status: Time Limit Exceeded

Solution code:
from scipy.special import comb
import itertools

n, k = map(int, input().split())
x = list(map(int, input().split()))
X = []
m = 3*10**8

for v in itertools.combinations(x, k):
    X.append(list(v))

for i in range(comb(n, k, exact=True)):
    a = min(abs(min(X[i]))+abs(max(X[i])-min(X[i])), abs(max(X[i]))+abs(max(X[i])-min(X[i])))
    if m > a:
        m = a
print(m)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

'''
x = sorted( x, key = lambda x: abs(x) )[ : K ]
x.sort()

m, M = x[ 0 ], x[ - 1 ]
print( abs( M - m ) + min( abs( m ), abs( M ) ))
'''

ret = 10 ** 18
for i in range( N - K + 1 ):
  s = x[ i: K + i ]
  l, r = s[0], s[ -1 ]
  ret = min( ret, abs( l - r ) + min( abs( r ), abs( l ) ) )
print( ret )

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
x = list(map(int, input().split()))
m = 10000000000000
for i in range(N-K+1):
  X = x[i:i+K]
  if X[0]*X[K-1] <= 0: # 区間に0を含む時
    m = min(m, 2*abs(X[0])+X[K-1], abs(X[0])+2*X[K-1])
  elif X[0]>0:
    m = min(m, X[K-1])
  else:
    m = min(m, abs(X[0]))
print(m)

Submission status: Time Limit Exceeded

Solution code:
from bisect import*
n,k,*a=map(int,open(0).read().split())
if 0 in a:
    k-=1
    a.remove(0)
#print(a)
ans=[]
for i in range(-k,1):
    b=a[bisect(a,0)+i:bisect(a,0)+i+k]
    if len(b)==0:
        continue
    if len(b)==k:
        #print(b)
        ans.append(abs(b[0])+abs(b[-1]-b[0]))
        ans.append(abs(b[-1])+abs(b[-1]-b[0]))
print(min(ans or [0]))

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,input().split())
x=list(map(int,input().split()))
ans=10000000000000000000
for i in range(0,N-K+1):
    ls=0
    rs=0

    for j in range(i,i+K):
        if(x[j]<0):
            ls=max(abs(x[j]),ls)
        else:
            rs=max(abs(x[j]),rs)
    ans=min(ls+rs+min(ls,rs),ans)

print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
a,b = map(int,input().split(" "))
ar = list(map(int,input().split(" ")))
cr = []
for i in range(a-b+1):
    br = ar[i:i+b]
    if br[0] > 0 and br[b-1] > 0:
        cr.append(br[b-1])
    elif br[0] < 0 and br[b-1] < 0:
        cr.append(br[0] * -1)
    else:
        r = abs(br[0]-br[b-1]) + abs(0 - br[b-1])
        l = abs(br[0]-br[b-1]) + abs(0 - br[0])
        cr.append(min(l,r))
print(min(cr))

Submission status: Time Limit Exceeded

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

ans = -1

for i in range(N - K + 1):
    px = x[i:i+K]
    xl = px[0]
    xr = px[-1]
    tmp = min(abs(xl),abs(xr)) + xr - xl
    if ans == -1 or tmp < ans:
        ans = tmp
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
input_data = input().split(" ")                                                                      
data = [int(n) for n in input_data]

N = data[0]
K = data[1]

candlePlot = input().split(" ")
candlePlot = [int(n) for n in candlePlot]

answerBuff = []

buffSum = 0 

formerCandlePlot = 0 

for n in range(N-K+1):
    
    candlePlotBuff = candlePlot[n:n+K]

    for m in candlePlotBuff:
        buffSum += abs(m - formerCandlePlot)
        formerCandlePlot = m 
    
    answerBuff.append(buffSum)
    formerCandlePlot = 0 
    buffSum = 0 

    candlePlotBuff.reverse()
    for m in candlePlotBuff:
        buffSum += abs(m - formerCandlePlot)
        formerCandlePlot = m 
    
    answerBuff.append(buffSum)
    formerCandlePlot = 0 
    buffSum = 0 

print(min(answerBuff))

Submission status: Time Limit Exceeded

Solution code:
def center_search(arr):
    if len(arr) == 1:
        return 0

    i = len(arr) // 2 - 1
    j = len(arr) // 2

    if arr[0] >= 0: 
        return 0
    elif arr[-1] < 0:
        return len(arr)

    while not (arr[i] < 0 <= arr[j]):

        if arr[i] == 0:
            return i
        elif arr[i] > 0:
            i = i // 2 - 1
            j = i // 2
        elif arr[j] < 0:
            i += (len(arr) - i) // 2 - 1
            j += (len(arr) - i) // 2

    return j

def find_dist(k, arr):

    center_i = center_search(arr)
    # print("center_i: {}".format(center_i))

    if center_i >= len(arr):
        return abs(arr[center_i-k]) 
    elif center_i <= 0:
        return abs(arr[center_i+k-1]) 
    
    i = max(0, center_i-k)
    min_dist = None

    while i <= center_i and i + k <= len(arr):
        if i == center_i:
            dist = arr[i + k - 1]
        elif i + k == center_i:
            dist = abs(arr[i])
        else:
            left_dist = abs(arr[i])
            right_dist = arr[i+k-1]
            dist = left_dist * 2 + right_dist if left_dist < right_dist else right_dist * 2 + left_dist 

        if min_dist is None or dist < min_dist:
            min_dist = dist
        i += 1

    # while i >= -1 and (not len(right) == k-i-2):
    #     left_dist = None if i < 0 else left[i]
    #     right_dist = None if k-i-2 < 0 else right[k-i-2]

    #     if right_dist is None:
    #         dist = left_dist
    #     elif left_dist is None: 
    #         dist = right_dist
    #     else:
    #         dist = left_dist * 2 + right_dist if left_dist < right_dist else right_dist * 2 + left_dist 

    #     if min_dist is None or dist < min_dist:
    #         min_dist = dist

    #     i -= 1

    return min_dist

if __name__ == "__main__":

    # assert center_search([0]) == 0
    # assert center_search([0, 1]) == 0
    # assert center_search([0, 1, 2]) == 0
    # assert center_search([1, 2]) == 0
    # assert center_search([1, 2, 4]) == 0
    # assert center_search([-1, 0]) == 1
    # assert center_search([-2, -1, 0]) == 2
    # assert center_search([-1, 1]) == 1
    # assert center_search([-1, 1, 2]) == 1
    # assert center_search([-1, 0, 1]) == 1
    # assert center_search([-2, -1, 0, 1]) == 2
    # assert center_search([-2, -1, 1]) == 2
    # assert center_search([-10, -2, -1, 0, 1, 2]) == 3
    # assert center_search([-10, -2, -1, 1, 2]) == 3
    # assert center_search([-10, -2, -1, 2]) == 3
    # assert center_search([-10, -2, -1]) == 3

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

    print(find_dist(k, arr))
    # print(find_dist(1,[0]))
    # print(find_dist(1,[5]))
    # print(find_dist(1,[-5]))
    # print(find_dist(1,[-10, 0]))
    # print(find_dist(1,[0, 10]))
    # print(find_dist(1,[10, 20]))
    # print(find_dist(2,[10, 20]))
    # print(find_dist(1,[-10,10]))
    # print(find_dist(2,[-10, 0]))
    # print(find_dist(2,[-10, -5]))
    # print(find_dist(2,[-30, -10, -5]))
    # print(find_dist(3,[-30, -10, -5]))
    # print(find_dist(2,[0, 10, 20]))
    # print(find_dist(2,[-10,10, 20]))
    # print(find_dist(1,[0, 10, 20]))
    # print(find_dist(1,[-10,10, 20]))
    # print(find_dist(2,[-10, 0, 20]))
    # print(find_dist(2,[0, 10, 20]))
    # print(find_dist(2,[-10,10, 20]))
    # print(find_dist(1,[-20, 0, 10]))
    # print(find_dist(1,[-20, -10,10]))
    # print(find_dist(2,[-20, -10, 0]))
    # print(find_dist(2,[-20, 0, 10]))
    # print(find_dist(2,[-20, -10,10]))
    # print(find_dist(3,[0, 10, 20]))
    # print(find_dist(3,[-10,10, 20]))
    # print(find_dist(3,[0, 10, 20]))
    # print(find_dist(3,[-10,10, 20]))
    # print(find_dist(3,[-10, 0, 20]))
    # print(find_dist(3,[0, 10, 20]))
    # print(find_dist(3,[-10,10, 20]))
    # print(find_dist(3,[-20, 0, 10]))
    # print(find_dist(3,[-20, -10,10]))
    # print(find_dist(3,[-20, -10, 0]))
    # print(find_dist(3,[-20, 0, 10]))
    # print(find_dist(3,[-10, 10, 20]))
    # print(find_dist(3,[-200, 10, 20]))
    # print(find_dist(3,[-10,10, 20]))
    # print(find_dist(3,[-20, -5, 10]))
    # print(find_dist(3,[-20, -10,10]))
    # print(find_dist(3,[-20, -10, -5]))
    # print(find_dist(3,[-20, 5, 10]))
    # print(find_dist(3,[-20, -10, -5]))
    # print(find_dist(3,[-50, -20, -10, -5]))
    # print(find_dist(3,[-50, -40, -20, -10, -5]))
    # print(find_dist(4,[-50, -40, -20, -10, -5]))
    # print(find_dist(6,[-50, -40, -20, -10, -5,0]))

Submission status: Time Limit Exceeded

Solution code:
def center_search(arr):
    if len(arr) == 1:
        return 0

    i = len(arr) // 2 - 1
    j = len(arr) // 2

    if arr[0] >= 0: 
        return 0
    elif arr[-1] < 0:
        return len(arr)

    while not (arr[i] < 0 <= arr[j]):

        if arr[i] == 0:
            return i
        elif arr[i] > 0:
            i = i // 2 - 1
            j = i // 2
        elif arr[j] < 0:
            i += (len(arr) - i) // 2 - 1
            j += (len(arr) - i) // 2

    return j

def find_dist(k, arr):

    center_i = center_search(arr)
    left = arr[:center_i]
    right = arr[center_i:]

    left = list(map(abs, left[::-1]))

    if len(left) == 0:
        return right[k-1]
    elif len(right) == 0:
        return left[k-1]
    
    i = min(k-1, len(left)-1)
    min_dist = None

    while i >= -1 and (not len(right) == k-i-2):
        left_dist = None if i < 0 else left[i]
        right_dist = None if k-i-2 < 0 else right[k-i-2]

        if right_dist is None:
            dist = left_dist
        elif left_dist is None: 
            dist = right_dist
        else:
            dist = left_dist * 2 + right_dist if left_dist < right_dist else right_dist * 2 + left_dist 

        if min_dist is None or dist < min_dist:
            min_dist = dist

        i -= 1

    return min_dist

if __name__ == "__main__":

    # assert center_search([0]) == 0
    # assert center_search([0, 1]) == 0
    # assert center_search([0, 1, 2]) == 0
    # assert center_search([1, 2]) == 0
    # assert center_search([1, 2, 4]) == 0
    # assert center_search([-1, 0]) == 1
    # assert center_search([-2, -1, 0]) == 2
    # assert center_search([-1, 1]) == 1
    # assert center_search([-1, 1, 2]) == 1
    # assert center_search([-1, 0, 1]) == 1
    # assert center_search([-2, -1, 0, 1]) == 2
    # assert center_search([-2, -1, 1]) == 2
    # assert center_search([-10, -2, -1, 0, 1, 2]) == 3
    # assert center_search([-10, -2, -1, 1, 2]) == 3
    # assert center_search([-10, -2, -1, 2]) == 3
    # assert center_search([-10, -2, -1]) == 3

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

    print(find_dist(k, arr))

Submission status: Time Limit Exceeded

Solution code:
a,b = map(int,input().split())

c = list(map(int,input().split()))
for i in range(len(c)-b+1):
    k = c[i:i+b]
    if k[0] * k[-1] < 0:
        if i == 0:
            m = abs(k[0]) + k[-1] +abs(min(k[0],k[-1]))
        else:
            m = min(m,abs(k[0]) + k[-1] +abs(min(k[0],k[-1])))
    else:
        if i == 0:
            m = max(abs(k[0]),abs(k[-1]))
        else:
            m = min(m,max(abs(k[0]),abs(k[-1])))

print(m)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000)

import copy

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

if((0 in x) == True):
    flag = n*[1]
    flag[x.index(0)] = 0
    state = x.index(0)
    count = 1
else:
    x.append(0)
    x = sorted(x)
    flag = (n+1)*[1]
    flag[x.index(0)] = 0
    state = x.index(0)
    count = 0

def search(x, flag, state, count, time, ans):
    if(count == k):
        if(ans > time): ans = time
        return ans

    if(sum(flag[:state]) != 0):
        tmp_state = state
        tmp_time = time
        while(True):
            state -= 1
            if(flag[state] == 1): break
        flag[state] = 0
        count += 1
        time += x[tmp_state] - x[state]

        ans = search(x, flag, state, count, time, ans)
        
        time = tmp_time
        count -= 1
        flag[state] = 1
        state = tmp_state

    if(sum(flag[state:]) != 0):
        tmp_state = state
        tmp_time = time
        while(True):
            state += 1
            if(flag[state] == 1): break
        flag[state] = 0
        count += 1
        time += x[state] - x[tmp_state]

        ans = search(x, flag, state, count, time, ans)
        
        time = tmp_time
        count -= 1
        flag[state] = 1
        state = tmp_state

    return ans

ans = search(x, flag, state, count, 0, int(1e9))

print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
x = list(map(int, input().split()))
 
ans = []
 
for _ in range(n - k + 1):
    a = abs(x[k + _ - 1]) + abs(x[k + _ - 1] - x[_])
    b = abs(x[_]) + abs(x[_] - x[k + _ - 1])
    
    ans.append(min(a, b))
 
print(min(ans))

Submission status: Accepted

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