# Maximum number of inversions that can be removed by swapping two elements?

I have come across a question that is a bit hard to understand due to its wording, I may havecome up with a possible solution, but I don't know if it's correct. Can you please help me? Thanks in advance!

Question

Suppose we exchange elements $a[i]$ and $a[j]$, where $j > i$, which are originally out of order.

For example, $a = [2,8,3,7,1,5,6]$ and we exchange the second and sixth elements, we have $[2,5,3,7,1,8,6]$.

The array has now fewer inversions. What is the maximum number of inversions that can be removed if we exchange $a[i]$ and $a[j]$?

Take an array and sort it in reverse order. The first element would have the most inversions. We switch it with the last element and the number of inversions decrease drastically.

The maximum number of inversions would be $j-i+n-2$.

My concern

Since the question doesn't say anything about me being allowed to change the order of the array, I don't know if my proposed answer is the one they were aiming for.

The question is indeed not completely clear, but they definitely wanted you to search the "worst possible" array $a$ (the one leading to the largest number of removed inversions). Otherwise there is nothing to do - just look at the array and calculate the number of inversions resulting from the swap.
What is somewhat less clear is whether they also wanted you to optimize over $i$ and $j$. Your answer, which doesn't assume that, is on the safe side.
• No - rather, that for given $i,j$, the amount of inversions removed that you obtain is the maximal over all choices of $a$. That may be obvious, and indeed the proof is not difficult, but it is part of the proof. The proof has two parts: (i) this particular array results in so many inversions removed, (ii) all arrays result in at most as many inversions removed. – Yuval Filmus Oct 24 '13 at 16:08