#include #include #include #include #include using namespace std; #define fi first #define sc second #define mkp make_pair #define pii pair typedef long long ll; const int N=2e5+5,oo=1e9,mod=998244353,G=3,invG=(mod+1)/G; inline int read() { int x=0,flag=0;char ch=getchar(); while(ch<'0'||ch>'9') {flag|=(ch=='-');ch=getchar();} while('0'<=ch&&ch<='9') {x=(x<<3)+(x<<1)+ch-'0';ch=getchar();} return flag?-x:x; } inline int mx(int x,int y) {return x>y?x:y;} inline int mn(int x,int y) {return x0?x:-x;} int n,k,a[N],fr[N],L[N],minn[N]; priority_queue Q1; priority_queue Q3,Q4; priority_queue< pii,vector,greater > Q2; int main() { n=read();k=read(); for(int i=1;i<=n;++i) a[i]=read(); for(int i=1;i<=n;++i) { fr[i]=(i-2)/(k-1)+1; if(!L[fr[i]]) L[fr[i]]=i; } minn[n]=a[n]; for(int i=n-1;i>=1;--i) minn[i]=mn(minn[i+1],a[i]); ll ans=a[k],sum=0; for(int i=n,pos;i>k;--i) { pos=fr[i]*k; if(pos<=n&&Q1.size()==fr[i]-1) { if(Q3.top()>=pos) ans=min(ans,a[i]+sum); else ans=min(ans,a[i]+sum-Q1.top().fi+minn[pos]); } Q2.push(mkp(a[i],i)); while(!Q2.empty()&&Q1.size()fr[i-1]-1) { Q2.push(Q1.top()),sum-=Q1.top().fi; Q4.push(Q1.top().sc); Q1.pop(); } while(!Q1.empty()&&!Q2.empty()&&Q1.top()>Q2.top()) { sum=sum-Q1.top().fi+Q2.top().fi; Q3.push(Q2.top().sc);Q4.push(Q1.top().sc); pii tmp=Q1.top();Q1.pop(); Q1.push(Q2.top());Q2.pop(); Q2.push(tmp); } while(!Q3.empty()&&!Q4.empty()&&Q3.top()==Q4.top()) Q3.pop(),Q4.pop(); } printf("%lld\n",ans); return 0; }