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: Runtime Error

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import bisect


def solve():
    n, k = map(int, input().split())
    al = [int(i) for i in input().split()]

    ans = sum(abs(i) for i in al)
    flag0 = 0 in al
    if flag0:
        k -= 1
        n -= 1
        if k == 0:
            print(0)
            return
        al.remove(0)
    nc = bisect.bisect_left(al, 0)
    for i in range(n):
        if i < 0 or i + k - 1 >= n:
            break
        if al[i] < 0 and al[i + k - 1] < 0:
            t1 = min(abs(al[i], al[i + k - 1]))
        else:
            t1 = min(abs(al[i]) * 2 + abs(al[i + k - 1]),
                     abs(al[i]) + abs(al[i + k - 1]) * 2)
        if al[i] > 0 and al[i + k - 1] > 0:
            t2 = min(abs(al[i], al[i + k - 1]))
        else:
            t2 = min(abs(al[i]) * 2 + abs(al[i + k - 1]),
                     abs(al[i]) + abs(al[i + k - 1]) * 2)
        t = min(t1, t2)
        ans = min(ans, t)
    for i in range(n - 1, -1, -1):
        if i - k + 1 < 0 or i >= n:
            break
        if al[i] < 0 and al[i - k + 1] < 0:
            t1 = abs(al[i - k + 1], al[i])
        else:
            t1 = min(abs(al[i - k + 1]) * 2 + abs(al[i]),
                     abs(al[i - k + 1]) + abs(al[i]) * 2)
        if al[i] > 0 and al[i - k + 1] > 0:
            t2 = abs(al[i - k + 1], al[i])
        else:
            t2 = min(abs(al[i - k + 1]) * 2 + abs(al[i]),
                     abs(al[i - k + 1]) + abs(al[i]) * 2)
        t = min(t1, t2)
        ans = min(ans, t)
    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Runtime Error

Solution code:
import bisect

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

zero_ind=bisect.bisect_left(x,0)
"""
print("max",0,k-zero_ind-1)
print("min",k,n-zero_ind)
print("max",1,k-n+zero_ind-1)
print("min",k,zero_ind+2)
"""
v,w=10**9,10**9
if(n-zero_ind >= k):v=abs(x[zero_ind+k-1])
if(zero_ind >= k):w=abs(x[zero_ind-k])

y=[abs(x[zero_ind+i])+abs(x[zero_ind+i]-x[zero_ind-(k-i)+1]) for i in range(max(0,k-zero_ind-1),min(k,n-zero_ind))]
z=[abs(x[zero_ind-i])+abs(x[zero_ind-i]-x[zero_ind+(k-i)-1]) for i in range(max(1,k-n+zero_ind-1),min(k,zero_ind+2))]

"""
for i in range(k):
    print(abs(x[zero_ind+i]))
    print(x[zero_ind-(k-i)+1])

for i in range(1,k):
    print(abs(x[zero_ind-i]))
    print(x[zero_ind+(k-i)-1])
"""
print(min([v,w]+y+z))
"""
print(y)
print(z)
"""

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
a=list(map(int, input().split()))
b=list(map(abs, a))
i=b.index(min(b))
c=list(filter(lambda x: x>=0, a))
e=sorted(c)
d=list(map(abs, filter(lambda x: x<0, a)))
f=sorted(d)

lp=len(c)
lm=len(d)
s=[]
if 0 in a:
    K -=1
if K==0:
    print(0)
elif K==N:
    print(min(2*e[lp-1]+f[lm-1],2*f[lm-1]+e[lp-1]))
elif lp==0:
    print(f[lm-1])
elif lm==0:
    print(e[lp-1])
else:
    for i in range(lp):
        if K-i<=lm:
            if i==K:
                u=e[i-1]
            else:
                u=2*e[i-1]+f[K-i-1]
            s.append(u)
    for t in range(lm):
        if K-t<=lp:
            if t==K:
                q=f[t-1]
            else:
                q=2*f[t-1]+e[K-t-1]
            s.append(q)

    print(min(s))

Submission status: Runtime Error

Solution code:
import bisect

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

zero_ind=bisect.bisect_left(x,0)
"""
print(max(0,k-zero_ind-1))
print(min(k,n-zero_ind))
print(max(1,k-n+zero_ind-1))
print(min(k+1,zero_ind+2))
"""
v,w=10**9,10**9
if(n-zero_ind >= k):v=abs(x[zero_ind+k-1])
if(zero_ind >= k):w=abs(x[zero_ind-k])

y=[abs(x[zero_ind+i])+abs(x[zero_ind+i]-x[zero_ind-(k-i)+1]) for i in range(max(0,k-zero_ind-1),min(k,n-zero_ind,zero_ind+k-1))]
z=[abs(x[zero_ind-i])+abs(x[zero_ind-i]-x[zero_ind+(k-i)-1]) for i in range(max(1,k-n+zero_ind-1),min(k+1,zero_ind+2,zero_ind+k))]

"""
for i in range(k):
    print(abs(x[zero_ind+i]))
    print(x[zero_ind-(k-i)+1])

for i in range(1,k):
    print(abs(x[zero_ind-i]))
    print(x[zero_ind+(k-i)-1])
"""
print(min([v,w]+y+z))
"""
print(y)
print(z)
"""

Submission status: Runtime Error

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

if((0 in x) == True):
    state = x.index(0)
    count = 1
else:
    x.append(0)
    x = sorted(x)
    state = x.index(0)
    count = 0

ans = int(1e9)
for left in range(k-count+1):
    right = k - count - left
    if(((state - left) >= 0) and ((state + right) <= (len(x)))):
        if(right > 0): tmp = -2 * x[state-left]
        else: tmp = -1 * x[state-left]
        tmp += x[state+right]
        if(ans > tmp): ans = tmp

print(ans)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
a=list(map(int, input().split()))
if 0 in a:
    K -=1
if K==0:
    print(0)
else:
    b=list(map(abs, a))
    i=b.index(min(b))
    c=list(filter(lambda x: x>=0, a))
    e=sorted(c)
    d=list(map(abs, filter(lambda x: x<0, a)))
    f=sorted(d)

    lp=len(c)
    lm=len(d)
    s=[]
    v=[]
    for i in range(lp):
        if K-i<=lm:
            if i==K:
                u=e[i-1]
            else:
                u=2*e[i-1]+f[K-i-1]
            s.append(u)
    for t in range(lm):
        if K-t<=lp:
            if t==K:
                q=f[t-1]
            else:
                q=2*f[t-1]+e[K-t-1]
            s.append(q)

    print(min(s))

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
a=list(map(int, input().split()))
if 0 in a:
  K -=1
b=list(map(abs, a))
i=b.index(min(b))
c=list(filter(lambda x: x>=0, a))
e=sorted(c)
d=list(map(abs, filter(lambda x: x<0, a)))
f=sorted(d)

lp=len(c)
lm=len(d)
s=[]
v=[]
for i in range(lp):
    if K-i<=lm:
        if i==K:
            u=e[i-1]
        else:
            u=2*e[i-1]+f[K-i-1]
        s.append(u)
for t in range(lm):
    if K-t<=lp:
        if t==K:
            q=f[t-1]
        else:
            q=2*f[t-1]+e[K-t-1]
        s.append(q)

print(min(s))

Submission status: Runtime Error

Solution code:
import math

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

plus = [0]
minus = []
zeroExist = 0

for i in range(n):
    if x[i] > 0:
        plus.append(x[i])
    elif x[i] == 0:
        zeroExist = 1
    else:
        minus.append(-x[i])
minus.append(0)
minus = list(reversed(minus))

# for i in range(1, len(minus)):
# minus[i] += minus[i-1]

# print(plus)
# print(minus)

if zeroExist == 1:
    k -= 1

cost = math.inf
for i in range(k+1):
    if i < len(plus) and k - i < len(minus):
        #print(i)
        if i == 0 or i == k:
            cost = min(cost, plus[i] + minus[k - i])
        else:
            cost = min(cost, plus[i] + minus[k - i]
                       + min(plus[i], minus[k-i]))
        #print("{}:{}".format(i, cost))
print(cost)

Submission status: Runtime Error

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

for i in range(n):
    if x[i] == 0:
        b = i
        start = True
        break
    elif x[i] > 0:
        b = i
        start = False
        break

if start:
    del x[b]
    k -= 1


if k == 0:
    m = 0
else:
    if b >= k:
        m1 = abs(x[b-k])
    else:
        m1 = None

    if n-b >= k:
        m2 = abs(x[b+k-1])
    else:
        m2 = None

    m = max(abs(2*x[0]), abs(2*x[-1]))
    for i in range(1, k):
        if b-i >= 0 and b-i+k-1 < n:
            m = min(2*abs(x[b-i])+abs(x[b-i+k-1]),abs(x[b-i])+2*abs(x[b-i+k-1]), m)

    if m1:
        m = min(m, m1)
    if m2:
        m = min(m, m2)

print(m)

Submission status: Runtime Error

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 n == 1:
	print(abs(x[0]))
elif x[0] >= 0:
	print(x[k - 1])
elif x[-1] <= 0:
	print(-x[-k - 1])
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(0, k - pos - 1), min(k - 1, n - pos)):
		#print(i)
		right = x[pos + i]
		left = -x[pos - (k - i - 1)]
		#print(right, left)
		ans = min(ans, 2 * right + left, 2 * left + right)

	print(ans)

Submission status: Runtime Error

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 N == 1:
        ans = abs(x)
    if i +  K  > N and i > 0:
        break
    num = abs(xs[ i + K - 1 ] - xs[i]) + abs(xs[i])
    num1 = abs(xs[ i + K - 1 ] - xs[i]) + abs(xs[i + K -1])
    ans = min([num,num1,ans])
print(ans)

Submission status: Runtime Error

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

for i in range(n):
    if x[i] == 0:
        b = i
        start = True
        break
    elif x[i] > 0:
        b = i
        start = False
        break

if start:
    del x[b]
    k -= 1


if k == 0:
    m = 0
else:
    if b >= k:
        m1 = abs(x[b-k])
    else:
        m1 = None

    if n-b >= k:
        m2 = abs(x[b+k-1])
    else:
        m2 = None

    m = max(abs(2*x[0]), abs(2*x[-1]))
    for i in range(1, k+1):
        if b-i >= 0 and b-i+k-1 < n:
            m = min(2*abs(x[b-i])+abs(x[b-i+k-1]),abs(x[b-i])+2*abs(x[b-i+k-1]), m)

    if m1:
        m = min(m, m1)
    if m2:
        m = min(m, m2)

print(m)

Submission status: Runtime Error

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 - 1])
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(0, k - pos - 1), min(k - 1, n - pos)):
		#print(i)
		right = x[pos + i]
		left = -x[pos - (k - i - 1)]
		#print(right, left)
		ans = min(ans, 2 * right + left, 2 * left + right)

	print(ans)

Submission status: Runtime Error

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

for i in range(n):
    if x[i] == 0:
        b = i
        start = True
        break
    elif x[i] > 0:
        b = i
        start = False
        break

if start:
    del x[b]
    k -= 1


if k == 0:
    m = 0
else:
    if b >= k:
        m1 = abs(x[b-k])
    else:
        m1 = None

    if n-b >= k:
        m2 = abs(x[b+k-1])
    else:
        m2 = None

    m = max(abs(2*x[0]), abs(2*x[-1]))
    for i in range(k):
        if b-i >= 0 and b-i+k-1 < n:
            m = min(2*abs(x[b-i])+abs(x[b-i+k-1]),abs(x[b-i])+2*abs(x[b-i+k-1]), m)

    if m1:
        m = min(m, m1)
    if m2:
        m = min(m, m2)

print(m)

Submission status: Runtime Error

Solution code:
import itertools as it
import collections as col
import bisect

import sys
sys.setrecursionlimit(10000)

def main():
    N, K = [int(x) for x in input().split()]
    reqs = [int(x) for x in input().split()]

    if K == 1:
       return abs(reqs[0])

    index_p = bisect.bisect_left(reqs, 0)
    index_n = index_p - 1
    for _ in range(K):
        if index_p > N:
            index_n -= 1
        elif index_n < 0:
            index_p += 1
        elif (abs(reqs[index_p]) < abs(reqs[index_n])):
            index_p += 1
        else:
            index_n -= 1

    if reqs[index_p-1] < 0:
        return abs(reqs[index_n+1]) 

    if reqs[index_n+1] > 0:
        return abs(reqs[index_p-1])
    
    a = min(abs(reqs[index_p-1]), abs(reqs[index_n+1]))
    b = max(abs(reqs[index_p-1]), abs(reqs[index_n+1]))

    return 2*a + b
    
if __name__ == '__main__':
    print(main())

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys


def main():
    n, k = [int(x) for x in sys.stdin.readline().rstrip().split(' ')]
    x = [int(x) for x in sys.stdin.readline().rstrip().split(' ')]

    c = 0
    while x[c] < 0 and c<n:
        c += 1


    def getCost(l, r):
        if l<c and c<=r-1:
            return min(-x[l]*2+x[r-1], x[r-1]*2-x[l])
        elif c>r-1:
            return -x[l]
        else:
            return x[r-1]
    cost = getCost(0, k)

    for i in range(1,n-k+1):
        cost = min(cost, getCost(i, i+k))
    
    print(cost)
        

      
if __name__=="__main__":
    main()

Submission status: Runtime Error

Solution code:
from bisect import bisect_left

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

num1 = bisect_left(xs, 0)
num2 = N - num1

d1s = [0] + [-x for x in xs[:num1]][::-1]
d2s = [0] + xs[num1:]

ans = float('inf')
for i in range(max(0, K - num2), num1 + 1):
    d1, d2 = d1s[i], d2s[K - i]
    ans = min(ans, d1 + d2 + min(d1, d2))

print(ans)

Submission status: Runtime Error

Solution code:
import itertools as it
import collections as col
import bisect

import sys
sys.setrecursionlimit(10000)

def intersect(a,b):
    return b[1] >= a[0]

def main():
    N, K = [int(x) for x in input().split()]
    reqs = [int(x) for x in input().split()]
    
    index_p = bisect.bisect_left(reqs, 0)
    index_n = index_p - 1

    for _ in range(K):
        if index_p > N:
            index_n -= 1
        elif index_n < 0:
            index_p += 1
        elif (abs(reqs[index_p]) < abs(reqs[index_n])):
            index_p += 1
        else:
            index_n -= 1
    if reqs[index_p-1] < 0:
        return abs(reqs[index_n+1]) 

    if reqs[index_n+1] > 0:
        return abs(reqs[index_p-1])
    
    a = min(abs(reqs[index_p-1]), abs(reqs[index_n+1]))
    b = max(abs(reqs[index_p-1]), abs(reqs[index_n+1]))

    return 2*a + b
    
if __name__ == '__main__':
    print(main())

Submission status: Runtime Error

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(K-len(R)+1, len(L)):
    if K - i < 0:
        continue

    ans = min(ans, abs(L[i]) * 2 + R[K-i])
print(ans)

Submission status: Runtime Error

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

vs = [int(x) for x in input().split()]

ns = [-v for v in vs if v < 0][::-1]
ps = [v for v in vs if v >= 0]

res = float('inf')
if len(ps) >= k:
    res = ps[k-1]
for i in range(min(k, len(ns))):
    if len(ps) + i + 1 < k: continue
    res = min(res, ns[i] * 2 + ps[k - i - 2])
    res = min(res, ns[i] + ps[k - i - 2] * 2)

print(res)

Submission status: Runtime Error

Solution code:
# C
N, K = map(int, input().split())
x_list = list(map(int, input().split()))

zero_cnt = 0
posi_ind = N+1
nega_ind = -1
# minus
for i in range(N):
    if x_list[i] == 0:
        zero_cnt = 1
        nega_ind = i-1
    elif x_list[i] > 0:
        posi_ind = i
        if zero_cnt == 0:
            nega_ind = i-1
        break
if zero_cnt == 1:
    K -= 1
res = 10**13
if K == 0:
    res = 0
for i in range(1, min(nega_ind+1, K)+1):
    p = x_list[posi_ind+(K-i-1)]
    n = -x_list[nega_ind - i + 1]
    r = min(2*p+n, 2*n+p)
    res = min(res, r)
l = posi_ind+(K-1)
if l < N:
    r = x_list[l]
    res = min(res, r)
print(res)

Submission status: Runtime Error

Solution code:
import sys
n,k = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
ma = []
pu = []
for i in range(n):
    if a[i] < 0:
        ma.append(a[i])
    else:
        pu.append(a[i])
for i in range(len(ma)):
    ma[i] = -ma[i]
ma.sort()
ans = float("inf")
for i in range(len(ma)):
    kota = 0
    kota += ma[i]
    if k <= i+1:
        ans = min(kota,ans)
    else:
        kota += ma[i]
        if (len(pu) >= k- i-2 and len(pu) != 0):
            kota += pu[k-i-2]
            ans = min(kota,ans)
for i in range(len(pu)):
    kota = 0
    kota += pu[i]
    if k <= i+1:
        ans = min(kota,ans)
    else:
        kota += pu[i]
        if (len(ma) >= k- i-2 and len(ma) != 0):
            kota += ma[k-i-2]
            ans = min(kota,ans)
print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq

# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
# MOD = 10**9 + 7

def solve(f):
    n, k = f.read_int_list()
    x = f.read_int_list()

    ans = float('inf')

    z = bisect.bisect_left(x, 0)
    if x[z] == 0: k -= 1
    if k <= z:
        ans = min(ans, abs(x[k-z]))
    else:
        ans = min(ans, abs(x[0])+x[k-1])
    if k <= n-z:
        ans = min(ans, x[z+k-1])
    else:
        ans = min(ans, x[-1]+abs(x[z-(n-k)]))

    return ans


class Reader(object):
    def __init__(self, filename=None):
        self.file = open(filename) if filename is not None else None
        self.case = 1

    def __readline(self):
        return self.file.next().strip() if self.file else raw_input()

    def next_case(self):
        self.file.next()
        self.case += 1

    def read_int(self): return int(self.__readline())
    def read_float(self): return float(self.__readline())
    def read_long(self): return long(self.__readline())
    def read_decimal(self): return decimal.Decimal(self.__readline())
    def read_str(self): return self.__readline()

    def read_int_list(self): return map(int, self.__readline().split())
    def read_float_list(self): return map(float, self.__readline().split())
    def read_long_list(self): return map(long, self.__readline().split())
    def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split())
    def read_str_list(self): return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv) > 1 else None
    f = Reader(filename)
    if f.file:
        while True:
            print "Case #%d\n"%f.case, solve(f)
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)