title: Given an array of integers, find the minimum number of steps to make each value equal
body: <p>I was practicing algorithms and came across this question. I was not able to solve it. I read the editorial provided but it doesn't explain the concept or idea behind the solution.here's the question link(<a href="https://www.hackerearth.com/practice/algorithms/sorting/heap-sort/practice-problems/algorithm/divide-apples/description/" rel="noreferrer">Question</a>).</p>
  
  <p><strong>Problem Statement--></strong></p>
  
  <p><strong>N</strong> boys are sitting in a circle. Each of them have some apples in their hand. You find that the total number of the apples can be divided by <strong>N</strong>. So you want to divide the apples equally among all the boys. But they are so lazy that each one of them only wants to give one apple to one of the neighbors at one step. Calculate the minimal number of steps to make each boy have the same number of apples. </p>
  
  <p><strong>Input</strong>--> First line of input is an integer <strong>N</strong> and second line contains  N numbers, indicating the number of apples of the <strong>i</strong>th boy.</p>
  
  <p><strong>Output</strong> --> Minimal number of steps to make each boy have the same number of apples. </p>
  
  <p>Here's the official implementation:</p>
  
  <pre><code>#include&lt;bits/stdc++.h&gt;
  #define mod 10001
  using namespace std;
  typedef long long LL;
  int main()
  {
      int n,a[10000],avg;
      LL b[mod],val=0,s=0,m;
      cin&gt;&gt;n;
      for(int i=0;i&lt;n;i++)
      {
          cin&gt;&gt;a[i];
          s+=a[i];
      }
      avg=s/n;
      b[0]=0;
      for(int i = 0; i &lt; n-1; i++){
          b[i+1] = b[i]+a[i]-avg;
      }
      sort(b,b+n);
      m = -b[n/2];
      for(int i=0;i&lt;n;i++)
      {
          val += abs(b[i]+m);
      }
      cout&lt;&lt;val;
      return 0;
  }
  </code></pre>
  
  <p>I am looking for an explanation for the above code/logic.How is it giving minimal number of steps? Any alternate solution/ approach (not code necessarily) is welcomed but please explain your approach.</p>
  
  <p>If anything is not clear, then please visit the link or ask in comments section.</p>