#include <iostream> #include <cstdio> #include <cstring> using namespace std; const int maxn=5e5+9; long long a[maxn]; long long dp[maxn],sum[maxn]; int que[maxn]; bool chk1(int k,int j,int i) { long long s1=(dp[j]-sum[j]+a[j+1]*j)-(dp[k]-sum[k]+a[k+1]*k); s1*=(a[i+1]-a[j+1]); long long s2=(dp[i]-sum[i]+a[i+1]*i)-(dp[j]-sum[j]+a[j+1]*j); s2*=(a[j+1]-a[k+1]); return s1>s2; } bool chk2(int k,int j,int i) { long long s=(dp[j]-sum[j]+a[j+1]*j)-(dp[k]-sum[k]+a[k+1]*k); return s<=(a[j+1]-a[k+1])*i; } int main() { // freopen("in.txt","r",stdin); int T; scanf("%d",&T); while(T--) { int n,m; scanf("%d %d",&n,&m); sum[0]=0; for(int i=1;i<=n;i++) { scanf("%lld",&a[i]); a[i]++; sum[i]=sum[i-1]+a[i]; } int front=1,end=0; dp[m]=sum[m]-a[1]*m; que[++end]=0; dp[0]=0; for(int i=1;i+m<=n;i++) { if(i>=m) { if(a[i+1]==a[que[end]+1]) { if(dp[i]<dp[que[end]]) { end--; while(front<end&&chk1(que[end-1],que[end],i)) end--; que[++end]=i; } } else { while(front<end&&chk1(que[end-1],que[end],i)) end--; que[++end]=i; } } while(front<end&&chk2(que[front],que[front+1],i+m)) front++; int u=que[front]; dp[i+m]=dp[u]+sum[i+m]-sum[u]-a[u+1]*(i+m-u); } printf("%lld\n",dp[n]); } return 0; }