Can someone explain this source code for balanced partitioning?
<p>Can someone please explain this code in detail? I've tried debugging it but i can't figure out how it produces the result. I've been searching for a solution for the problem and this is the code that I stumbled upon, it produces accurate solutions and I would like to know how it works. Many thanks.</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;stdio.h&gt;   
#include &lt;math.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;limits.h&gt;
using namespace std;


int BalancedPartition ( int a[] , int n ){

int sum = 0;
for( int i = 0 ; i &lt; n ; i++)
    sum += a[i];

int *s = new int[sum+1];

s[0] = 1;
for(int i = 1 ; i &lt; sum+1 ; i++)    s[i] = 0;

int diff = INT_MAX , ans;

for(int i = 0 ; i &lt; n ; i++)
{
    for(int j = sum ; j &gt;= a[i] ; j--)
    {
        s[j] = s[j] | s[j-a[i]];
        if( s[j] == 1 )
        {
            if( diff &gt; abs( sum/2 - j) )
            {
                diff = abs( sum/2 - j );
                ans = j;
            }

        }
    }
}
return sum-ans-ans;
}

int main()
{
    int n,result, arr[300];
    cin &gt;&gt;n;
    for(int i = 0; i &lt; n; i++)
    {
        cin&gt;&gt;arr[i];
}
result = BalancedPartition(arr,n);
cout &lt;&lt;abs(result); // The difference between the sums of the two subsets

return 0;
}
</code></pre>
