Maximize the sum

Given array A of size n we have to create an array B by re-arranging array A. Now we need to maximize the sum |A_i - B_i|, for all i. I think sorting A in increasing and B in decreasing order, then adding corresponding element will result in optimal solution. Is this correct or there can be a better algorithm ?
Thanks in advance.

2 Likes

its the optimal solution just make sure you are using an efficient function to sort the elements