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:
#! usr/bin/env python
# -*- coding: utf-8 -*-


def main():
    n, k = map(int, input().split())
    c = list(map(int, input().split()))

    ans = 10 ** 12
    for i in range(n-k+1):
        if c[i+k-1] <= 0:
            t = abs(c[i+k-1]-c[i])
        elif c[i] < 0 < c[i+k-1]:
            t = abs(c[i]) + abs(c[i+k-1]-c[i])
        else:
            t = c[i+k-1]

        ans = min(ans, t)


    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop
n,k=map(int,input().split())
h=[]
for x in map(int,input().split()):
    heappush(h,(abs(x),x))
s=[[]for _ in'12']
for _ in[0]*k:
    c,x=heappop(h)
    s[x>0]+=[c]
if len(s[0])==0:
    print(max(s[1]))
elif len(s[1])==0:
    print(max(s[0]))
else:
    a,b=map(max,s)
    if a>b:
        print(a+b*2)
    else:
        print(b+a*2)

Submission status: Time Limit Exceeded

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

import bisect

i=bisect.bisect_left(X,0)
L=max(0, bisect.bisect_right(X,0)-K)
R=min(N-1, bisect.bisect_left(X,0)+K-1)

ans=float('inf')
for i in range(L,R-K+2):
    t=0
    s=X[i:i+K]
    if s[-1]<=0:
        t+=abs(s[0])
    elif 0<=s[0]:
        t+=s[-1]
    else:
        t+=min(abs(s[0]),s[-1])*2+max(abs(s[0]),s[-1]) 
    # print(s,t)
    ans=min(ans,t)
print(ans)

Submission status: Time Limit Exceeded

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

import bisect

i=bisect.bisect_left(X,0)
L=max(0, bisect.bisect_right(X,0)-K)
R=min(N-1, bisect.bisect_left(X,0)+K-1)

ans=float('inf')
for i in range(L,R-K+2):
    t=0
    s=X[i:i+K]
    if s[0]<0:
        t+=abs(s[0])
    if 0<X[-1]:
        t+=t+s[-1]
    # print(s,t)
    ans=min(ans,t)
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque

# import fractions

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, K = il()
    X = il()

    ret = MAX
    for n in range(N - K + 1):
        C = X[n:n + K]
        ret = min(ret, abs(X[n]) + abs(X[n] - X[n+K-1]), abs(X[n+K-1]) + abs(X[n] - X[n+K-1]))
    print(ret)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque

# import fractions

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, K = il()
    X = il()

    ret = MAX
    for n in range(N - K + 1):
        C = X[n:n + K]
        ret = min(ret, abs(C[0]) + abs(C[0] - C[K-1]), abs(C[K-1]) + abs(C[0] - C[K-1]))
    print(ret)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from itertools import product

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]


def main():
    N, K = mi()
    x = list(mi())
    m = 10**100
    for i in range(N-K+1):
        l = x[i:i+K]
        tmp = min(abs(l[0]), abs(l[-1]))+(l[-1]-l[0])
        m = min(m, tmp)
    print(m)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n,k=map(int,input().split())
xs=list(map(int,input().split()))
a=float('inf')
for i in range(n-k+1):
    x=xs[i:i+k]
    l=abs(x[0])+abs(x[0]-x[-1])
    r=abs(x[-1])+abs(x[0]-x[-1])
    m=min(l,r)
    a=min(a,m)
print(a)

Submission status: Time Limit Exceeded

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

l2 = []
for _ in l1:
    if l1[0] >= 0:
        break
    num = l1.pop(0)
    l2.insert(0, num*(-1))


time = []

for i in range(K):
    if i > len(l1)-1:
        break
    if K-(i+1) > len(l2):
        continue
    if K-(i+1)-1 == -1:
        if len(l1) >= K:
            time.append(l1[K-1])
        break
    n1 = l1[i]
    n2 = l2[K-(i+1)-1]
    num = min(n1,n2)*2 + max(n1,n2)
    time.append(num)

if len(l2) >= K:
    time.append(l2[K-1])


print(min(time))

Submission status: Time Limit Exceeded

Solution code:
import itertools
import collections
n,k=map(int,input().split())
candle=list(map(int,input().split()))
com=list(itertools.product(["1","0"], repeat=n))
ans=200000000
for i in range(2**n):
  count=collections.Counter(com[i])
  if count["1"]==k:
    comtemp="".join(com[i])
    start=candle[comtemp.find("1")]
    end=candle[comtemp.rfind("1")]
    temp=0
    if start>=0:
      temp=abs(end)
      if temp<ans:
        ans=temp
    if end<=0:
      temp=abs(start)
      if temp<ans:
        ans=temp
    else:
      temp=min(abs(start), end)*2+max(abs(start), end)
      if temp<ans:
        ans=temp
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import collections
n,k=map(int,input().split())
candle=list(map(int,input().split()))
com=list(itertools.product([1,0], repeat=n))
ans=200000000
for i in range(2**n):
  count=collections.Counter(com[i])
  if count[1]==k:
    begin=0
    end=0
    cnt=0
    temp=0
    for j in range(n):
      if com[i][j]==1:
        cnt+=1
        if cnt==1:
          start=candle[j]
        elif cnt==k:
          end=candle[j]
    if start>=0:
      temp=abs(end)
      if temp<ans:
        ans=temp
    if end<=0:
      temp=abs(start)
      if temp<ans:
        ans=temp
    else:
      temp=min(abs(start), end)*2+max(abs(start), end)
      if temp<ans:
        ans=temp
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
#from decimal import *

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

for i in range(N-K+1):
	S = x[i:i+K]
	tmp = max(S)-min(S) + min(abs(max(S)), abs(min(S)))
	ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n, k = map(int, input().split())
x = np.array(list(map(int, input().split())))

ans = []
for i in range(n - k + 1):
    left = 0
    right = 0
    arr = x[i: i + k]
    if arr.min() < 0:
        left = (np.abs(arr[np.where(arr < 0)])).max()
    if arr.max() >= 0:
        right = (arr[np.where(arr >= 0)]).max()
    ans.append(min(left * 2 + right, left + right * 2))

print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
import sys
import os
import math
import bisect
import collections
import itertools
import heapq
import re
import queue

# import fractions

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, K = il()
    X = il()

    ret = MAX
    for n in range(N - K + 1):
        dis = X[n:n + K]
        l = abs(dis[0]) + abs(dis[0]-dis[K-1])
        r = abs(dis[K-1]) + abs(dis[K-1] - dis[0])
        ret = min(ret, l, r)
    print(ret)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import os
import math
import bisect
import collections
import itertools
import heapq
import re
import queue

# import fractions

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, K = il()
    X = il()

    ret = MAX
    for n in range(N - K + 1):
        T = X[n:n + K]
        l = abs(T[0]) + abs(T[0] - T[K-1])
        r = abs(T[K-1]) + abs(T[0] - T[K-1])
        ret = min(ret, l, r)
    print(ret)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import os
import math
import bisect
import collections
import itertools
import heapq
import re
import queue

# import fractions

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, K = il()
    X = il()

    ret = MAX
    for n in range(N - K + 1):
        T = X[n:n + K]
        l = abs(T[0]) + abs(T[0] - T[len(T)-1])
        r = abs(T[len(T)-1]) + abs(T[0] - T[len(T)-1])
        ret = min(ret, l, r)
    print(ret)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import os
import math
import bisect
import collections
import itertools
import heapq
import re
import queue

# import fractions

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, K = il()
    X = il()

    ret = MAX
    for n in range(N - K + 1):
        T = X[n:n + K]
        sm = min(abs(T[0]), abs(T[len(T)-1]))
        for t in range(len(T)-1):
            sm += abs(T[t] - T[t+1])
        ret = min(ret, sm)
    print(ret)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
xlis = list(map(int, input().split()))
ret = 10 ** 100
for i in range(n-k+1):
    cand = xlis[i:k+i]
    min_val = cand[0]
    max_val = cand[-1]
    if min_val * max_val >= 0:
        tmp = max(abs(min_val), abs(max_val))
        ret = min(ret, tmp)
    else:
        fst = min(abs(min_val), abs(max_val))
        lst = max(abs(min_val), abs(max_val))
        tmp = fst * 2 + lst
        ret = min(ret, tmp)

print(ret)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline


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


def readint():
    return int(input())


def readnums():
    return map(int, input().split())


def readstrs():
    return input().split()


def main():
    N, K = readnums()
    x = list(readnums())
    ans = 0
    for i in range(K, N + 1):
        l = x[i - K:i]
        if l[0] > 0:
            val = abs(l[-1])
        elif l[-1] < 0:
            val = abs(l[0])
        else:
            val = abs(l[0]) + abs(l[-1])
            val += min(abs(l[0]), abs(l[-1]))
        if not ans:
            ans = val
        else:
            ans = min(ans, val)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline


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


def readint():
    return int(input())


def readnums():
    return map(int, input().split())


def readstrs():
    return input().split()


def main():
    N, K = readnums()
    x = list(readnums())
    ans = 0
    for i in range(K, N + 1):
        l = x[i - K:i]
        if l[0] > 0:
            val = abs(max(l))
        elif l[-1] < 0:
            val = abs(min(l))
        else:
            val = abs(min(l)) + abs(max(l))
            val += min(abs(min(l)), abs(max(l)))
        if not ans:
            ans = val
        else:
            ans = min(ans, val)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline


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


def readint():
    return int(input())


def readnums():
    return map(int, input().split())


def readstrs():
    return input().split()


def main():
    N, K = readnums()
    x = list(readnums())
    ans = 0
    for i in range(K, N + 1):
        l = x[i - K:i]
        if min(l) > 0:
            val = abs(max(l))
        elif max(l) < 0:
            val = abs(min(l))
        else:
            val = abs(min(l)) + abs(max(l))
            val += min(abs(min(l)), abs(max(l)))
        if not ans:
            ans = val
        else:
            ans = min(ans, val)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline


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


def readint():
    return int(input())


def readnums():
    return map(int, input().split())


def readstrs():
    return input().split()


def main():
    N, K = readnums()
    x = list(readnums())
    ans = 0
    for i in range(K, N + 1):
        l = x[i - K:i]
        if all([m > 0 for m in l]):
            val = abs(max(l))
        elif all([m < 0 for m in l]):
            val = abs(min(l))
        else:
            val = abs(min(l)) + abs(max(l))
            val += min(abs(min(l)), abs(max(l)))
        if not ans:
            ans = val
        else:
            ans = min(ans, val)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, k = mi()
    L = lmi()
    ans = 2 ** 64 - 1
    for i in range(n - (k - 1)):
        if max(L[i:i+k]) <= 0:
            cost = abs(L[i])
        elif min(L[i:i+k]) >= 0:
            cost = L[i+k-1]
        else:
            cost = L[i+k-1] - L[i] + min(abs(L[i]), L[i+k-1])
        ans = min(ans, cost)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n,k = map(int,input().split())
x = list(map(int,input().split()))
flag = True
for i in range(n+1):
    if i == n or x[i] > 0:
        x.insert(i,0)
        zahyou = i
        break
ans = 10**18
for i in range(k+1):
    mainasu = 0
    purasu = 0
    flag = True
    for j in range(k):
        a = zahyou-k+i+j
        if  a >= 0 and a < n:
            if x[a] < 0:
                mainasu += x[a+1]-x[a]
            else:
                purasu += x[a+1]-x[a]
        else:
            flag = False
    if mainasu != 0 and purasu != 0:
        purasu += min(mainasu,purasu)
    if flag:
        ans = min(ans,mainasu+purasu)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect
n,k = map(int, input().split())
x = list(map(int, input().split()))
z = bisect.bisect_left(x,0)

ans=10**12
s=z-k+1
if s < 0:
  s=0
if z == 0:
  z+=1
for i in range(s,z):
  t=x[i:i+k]
  xl=min(t)
  xr=max(t)
  ans=min(ans,abs(xr)+abs(xr-xl),abs(xl)+abs(xr-xl))
print(ans)

Submission status: Time Limit Exceeded

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

ans=float('inf')
for i in range(n-k+1):
    nowx=x[i:i+k]
    if nowx[0]>=0 and nowx[-1]>=0:
        ans=min(ans, nowx[-1])
    elif nowx[0]<=0 and nowx[-1]<=0:
        ans=min(ans, abs(nowx[0]))
    elif nowx[0]<0 and nowx[-1]>=0:
        ans=min(ans, 2*abs(nowx[0])+nowx[-1], abs(nowx[0])+2*nowx[-1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline

def main():
    N, K = map(int, readline().rstrip().split())
    X = list(map(int, readline().rstrip().split()))
    len_m = len([x for x in X if x < 0])
    len_p = len([x for x in X if x > 0])
    ans = 10**10
    idx = max(0, len_m-K)
    s = [0] + X[idx:idx+K-1]
    for i in range(max(0, len_m-K), min(len_m+K, N-K+1)):
        s = s[1:]
        s.append(X[i+K-1])
        if len(s) != K:
            continue
        if s[0] < 0 and s[-1] > 0:
            c = min(abs(s[0]) * 2 + s[-1], abs(s[0]) + s[-1] * 2)
        else:
            c = max(abs(s[0]), abs(s[-1]))
        ans = min(ans, c)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline

def main():
    N, K = map(int, readline().rstrip().split())
    X = list(map(int, readline().rstrip().split()))
    len_m = len([x for x in X if x < 0])
    len_p = len([x for x in X if x > 0])
    ans = 10**10
    idx = max(0, len_m-K)
    s = [0] + X[idx:idx+K-1]
    for i in range(max(0, len_m-K), min(len_m+K, N-K+1)):
        s = s[1:] + [X[i+K-1]]
        if len(s) != K:
            continue
        if s[0] < 0 and s[-1] > 0:
            c = min(abs(s[0]) * 2 + s[-1], abs(s[0]) + s[-1] * 2)
        else:
            c = max(abs(s[0]), abs(s[-1]))
        ans = min(ans, c)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline

def main():
    N, K = map(int, readline().rstrip().split())
    X = list(map(int, readline().rstrip().split()))
    len_m = len([x for x in X if x < 0])
    len_p = len([x for x in X if x > 0])
    ans = 10**10
    for i in range(max(0, len_m-K), min(len_m+K, N-K+1)):
        s = X[i:i+K]
        if len(s) != K:
            continue
        if s[0] < 0 and s[-1] > 0:
            c = min(abs(s[0]) * 2 + s[-1], abs(s[0]) + s[-1] * 2)
        else:
            c = max(abs(s[0]), abs(s[-1]))
        ans = min(ans, c)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
def func(a):
    global alist
    cnt = 1
    for i in range(len(alist)):
        if abs(alist[i][0]) > abs(int(a)):
            alist[i][1] += 1
        else:cnt += 1
    alist.append([int(a),cnt])

    return int(a)



alist = []
n,k = map(int,input().split())
x = list(map(func,input().split()))#sort済み
anslist = []
for i in range(len(alist)):
    if alist[i][1] <= k:
        anslist.append(alist[i][0])

anslist.sort()
#print(alist)
#print(anslist)
if anslist[0] >= 0 and anslist[-1] >= 0:
    print(anslist[-1])

elif anslist[0] <= 0 and anslist[-1] <= 0:
    print(-anslist[0])

else:
    if anslist[-1] > -anslist[0]:
        print(-2*anslist[0] + anslist[-1])
    else:
        print(2*anslist[-1] - anslist[0])

Submission status: Time Limit Exceeded

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

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
ns = list(map(int, input().split()))
min_num = float('inf')
for i in range(n - k+1):
    l = ns[i:i + k]
    if l[-1] < 0:
        min_num = min(min_num, abs(l[0]))
    elif l[0] < 0 and l[-1] >= 0:
        min_num = min(min_num, abs(l[0]) * 2 + l[-1])
        min_num = min(min_num, abs(l[0]) + l[-1] * 2)
    else:
        min_num = min(min_num, l[-1])
print(min_num)

Submission status: Time Limit Exceeded

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

res_lst = []
for i in range(n-k+1):
  lst = xs[i:i+k]
  res = min(abs(lst[0]) + abs(lst[-1] - lst[0]), abs(lst[-1]) + abs(lst[0] - lst[-1]))
  res_lst.append(res)
print(min(res_lst))

Submission status: Time Limit Exceeded

Solution code:
N, K = map(int, input().split())
x = list(map(int, input().split()))
ans = 10 ** 8 * K
for i in range(N-K+1):
  for j in range(i+(K-1), N):
    a = min(abs(x[i]), abs(x[j])) + abs(x[i] - x[j])
    if ans > a:ans = a
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
N, K = map(int, input().split())
x = list(map(int, input().split()))
ans = 10 ** 8 * K
for i in range(N-K+1):
  for j in range(i+(K-1), N):
    a = abs(x[i]) + abs(x[i] - x[j])
    b = abs(x[j]) + abs(x[i] - x[j])
    if min(a, b) < ans:
      ans = min(a, b)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
N, K = map(int, input().split())
x = list(map(int, input().split()))
ans = 10 ** 8 * K
for v in itertools.combinations(x, K):
  a = abs(v[0]) + abs(v[-1] - v[0])
  b = abs(v[-1]) + abs(v[-1] - v[0])
  if min(a, b) < ans:
    ans = min(a, b)
print(ans)

Submission status: Time Limit Exceeded

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

ans = float('inf')
for i in range(n-k+1):
    l, r = X[i:i+k][0], X[i:i+k][-1]
    if r < 0:
        ans = min(abs(l), ans)
    elif 0 < l:
        ans = min(abs(r), ans)
    else:
        ans = min(min(abs(l), abs(r))*2+max(abs(l), abs(r)), ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
N, K = map(int, input().split())
x = list(map(int, input().split()))
ans = 10 ** 8 * K
for v in itertools.permutations(x, K):
  v = list(v)
  v.sort()
  a = abs(v[0]) + abs(v[-1] - v[0])
  b = abs(v[-1]) + abs(v[-1] - v[0])
  if min(a, b) < ans:
    ans = min(a, b)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,K=map(int,input().split())
X=list(map(int,input().split()))+[0]
ans=10**20

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

Submission status: Time Limit Exceeded

Solution code:
num = input().split(" ")
zahyou = input().split(" ")
zahyou_int = [int(i) for i in zahyou]
num[0] = int(num[0])
num[1] = int(num[1])

rousoku = []
time = 3 * 10 ** 8
for i in range(num[0]-num[1]+1):
    rousoku = zahyou_int[i:(i+num[1])]
    # print(rousoku)
    time_p = -min(0, min(rousoku)) * 2 + max(rousoku)
    time_m = max(0, max(rousoku)) * 2 - min(rousoku)
    if(min(time_p, time_m) < time):
        time = min(time_p, time_m)

print(time)

Submission status: Time Limit Exceeded

Solution code:
num = input().split(" ")
zahyou = input().split(" ")
zahyou_int = []
num[0] = int(num[0])
num[1] = int(num[1])
for i in zahyou:
    zahyou_int.append(int(i))

rousoku = []
time = 4 * 10 ** 8
for i in range(num[0]-num[1]+1):
    rousoku = zahyou_int[i:(i+num[1])]
    # print(rousoku)
    time_p = -min(0, min(rousoku)) * 2 + max(rousoku)
    time_m = max(0, max(rousoku)) * 2 - min(rousoku)
    if(time_p < time):
        time = time_p
    if(time_m < time):
        time = time_m
    # print(time)

print(time)

Submission status: Time Limit Exceeded

Solution code:
x,y = map(int,input().split())
t = list(map(int,input().split()))
ans = 1000000000000000000000000000000
for i in range(x-y+1):
    hani = t[i:i+y]
    if hani[0] <= 0 and 0 <= hani[-1]:
        ans = min(ans, abs(hani[-1]*2)+abs(hani[0]), abs(hani[-1])+abs(hani[0]*2))
    elif hani[-1] <= 0:
        ans = min(ans, abs(hani[0]))
    elif 0 <= hani[0]:
        ans = min(ans, abs(hani[-1]))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
x,y = map(int,input().split())

t = list(map(int,input().split()))

hani = []

for i in range(x-y+1):
    hani.append(t[i:i+y])
ans = 1000000000000000000000000000000
for i in range(len(hani)):
    if hani[i][0] <= 0 and 0 <= hani[i][-1]:
        ans = min(ans, abs(hani[i][-1]*2)+abs(hani[i][0]), abs(hani[i][-1])+abs(hani[i][0]*2))
    elif hani[i][-1] <= 0:
        ans = min(ans, abs(hani[i][0]))
    elif 0 <= hani[i][0]:
        ans = min(ans, abs(hani[i][-1]))
print(ans)