Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя greek__god

Автор greek__god, история, 4 года назад, По-английски

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.

  • Проголосовать: нравится
  • +7
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

yes, that's correct

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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().