➤ Problem Link : CANDY
👉 Hint : Use sorting
✅ C++ Solution :
#include<bits/stdc++.h> using namespace std; int main() { while(1) { int n; cin>>n; if(n==-1) break; int arr[n],i,j; int ans=0; for(i=0;i<n;i++) { cin>>arr[i]; ans+=arr[i]; } int x=ans%n; ans=ans/n; int cnt=0; if(x!=0) { cnt=-1; } else { sort(arr,arr+n); for(i=0,j=n-1;i<n,j>=0,j!=i;) { if(arr[j]>ans) { while(arr[i]<ans) { arr[i]+=1; arr[j]-=1; cnt+=1; if(arr[j]==ans) break; } if(arr[j]==ans) j--; else if(arr[i]==ans) ++i; } else j--; } } cout<<cnt<<endl; } }
Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook.
😇Happy Learning!!