Calculate difference of indices
1) I would change the inner for loop this way (very little optimization, unlikely it will bring better performance)

int ans=0;
int y=index-1;
for(int j=0; j&lt;y; j++)
{
    int diff = a[y] - a[j];

    if(diff &gt; 0)
        ans += diff;
    else
        ans -= diff;
}


2) You never store ans in the map.