I don't understand the logic behind the code

for(int k=1;k<=t;k++)
{
cin>>n>>p;arr[0]=0;
for(int i=1;i<=n;i++)
{
cin>>arr[i];
}
sort(arr+1, arr+n+1);
for(int i=1;i<=n;i++)
{
arr[i]+=arr[i-1];
}
int ans=1e18;;
for(int i=1;i+p-1<=n;i++)
{
int sum=arr[i+p-1] - arr[i-1];
int req=(arr[i+p-1]-arr[i+p-2])*p - sum;
ans=min(ans, req);
}
cout<<“Case #”<<k<<": "<<ans<<endl;
}
}

The question for the code is 2019 kickstart Round A.