Please read the new rule regarding the restriction on the use of AI tools. ×

greek__god's blog

By greek__god, history, 4 years ago, In English

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|$$$. 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 for this problem. Thanks in advance.

  • Vote: I like it
  • +7
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

yes, that's correct

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

There is a better algorythm in terms of complexity, since sorting is somewhat more than has to be done. We can also pair the elements by partitioning the array into two halfs, the upper one, and the lower one. And then pair any two elements from both halfs.

We can use nth_element() which works somewhat faster than sort().