After sorting both arrays Now each array is in non - decreasing order . Thus , we will now compare each element of the array and do the increment or decrement operation depending upon the value of array b [ ] .
for ( $ i = 0 ; $ i < $ n ; ++ $ i ) { if ( $ a [ $ i ] > $ b [ $ i ] ) $ result = $ result + abs ( $ a [ $ i ] - $ b [ $ i ] ) ; else if ( $ a [ $ i ] < $ b [ $ i ] ) $ result = $ result + abs ( $ a [ $ i ] - $ b [ $ i ] ) ; } return $ result ; }