I used the method of difference array to solve the problem - Problem link
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main() {
// your code goes here
long t;
cin>>t;
while(t--){
int n;cin>>n;
int m;cin>>m;
vector<int>a(n);
vector<int>dif(n);
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a.begin(),a.end());
dif[0]=a[0];
for(int i=1;i<n;i++){
dif[i]=a[i]-a[i-1];
}
int idx=n-1;
int op=0;
for(;idx>=0;idx--){
if(dif[idx]==0){continue;}
else{
op+=dif[idx];
if((idx-m)>=0){
dif[idx-m]+=dif[idx];
}else{
dif[0]+=dif[idx];
}
dif[idx]=0;
}
}
cout<<op-a[n-1]<<endl;
}
return 0;
}
it is giving the wrong answer. please help