import sys import math sys.setrecursionlimit(10**7) class lazysegki(): #区間和のセグメント木、葉の数N,要素ls def __init__(self,N,ls,mode='sum'): self.default = 0 self.func = (lambda x, y: x + y) self.N = N self.K = (N-1).bit_length() self.N0 = 1 << self.K self.dat = [self.default]*(2**(self.K+1)) #全体の配列を用意(maxなら-inf,minなら+infで未構築を表現)  self.lazy = [0]*(2**(self.K+1)) #遅延評価 for i in range(self.N): #葉の構築 self.dat[2**self.K+i] = ls[i] self.build() def build(self): for j in range(self.N0-1,0,-1): self.dat[j] = self.func(self.dat[j<<1],self.dat[j<<1|1]) #親が持つ条件 def leafvalue(self,x): #x番目の値を出力 return self.query(x,x+1) def update_add(self,x,y): #x番目にyを足す return self.updatel_add(x,x+1,y) def gindex(self,l, r): #伝播するインデックス列挙 L = l + self.N0; R = r + self.N0 lm = (L // (L & -L)) >> 1 rm = (R // (R & -R)) >> 1 lsindex = [] while L < R: if R <= rm: lsindex.append(R) if L <= lm: lsindex.append(L) L >>= 1; R >>= 1 while L: lsindex.append(L) L >>= 1 return lsindex def propagates(self,ids): for i in reversed(ids): v = self.lazy[i] if not v: continue self.lazy[i<<1] += v//2; self.lazy[i<<1|1] += v//2 self.dat[i<<1] += v//2; self.dat[i<<1|1] += v//2 self.lazy[i] = 0 def updatel_add(self,l, r, x):#区間にyを足す self.propagates(self.gindex(l, r)) L = self.N0 + l R = self.N0 + r ii = 0 while L < R: if L & 1: self.lazy[L] += x*(2**ii) self.dat[L] += x*(2**ii) L += 1 if R & 1: R -= 1 self.lazy[R] += x*(2**ii) self.dat[R] += x*(2**ii) L >>= 1 R >>= 1 ii += 1 for i in self.gindex(l, r): self.dat[i] = self.func(self.dat[i<<1],self.dat[i<<1|1])+self.lazy[i] def query(self,l, r): self.propagates(self.gindex(l, r)) L = self.N0 + l R = self.N0 + r vL = self.default vR = self.default while L < R: if L & 1: vL = self.func(vL,self.dat[L]) L += 1 if R & 1: R -= 1 vR = self.func(self.dat[R],vR) L >>= 1 R >>= 1 return self.func(vL,vR) N,K = map(int,input().split()) lsA = list(map(int,input().split())) minA = min(lsA) lsA2 = [i-minA for i in lsA] lsv = [0]*(N) lsv[0] = sum(lsA2) lsc = [0] c = 0 for i in range(1,N): lsv[i] = lsv[i-1]+(lsA2[i]-c)*(2*i-N) lsc.append(lsA2[i]-c) c += lsA2[i]-c if K == 0: print(-max(lsv)) exit() SG = lazysegki(N,lsA2) l = 0 r = K lsq = [sum(lsA2[:K])] for i in range(1,N): SG.updatel_add(0,i,lsc[i]) SG.updatel_add(i,N,-lsc[i]) while r < N and SG.leafvalue(l) > SG.leafvalue(r): l += 1 r += 1 lsq.append(SG.query(l,r)) lsans = [] for i in range(N): m = -(lsv[i]-lsq[i]) m += lsq[i] lsans.append(m) print(min(lsans))