Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Among all arrays with elements from the set {1, 2, …, n}, which array has the most inversions? How many inversions does it have?

Setup:
Let E[1 .. n] be an array of n distinct numbers.
Let i,j be indices of elements in array E.
If 1 ≤ i < j ≤ n and E[i] > E[j], then the pair of indices (i, j) is called an inversion of array E.

Question:
Among all arrays with elements from the set {1, 2, …, n}:
1. Which array has the most inversions?
2. How many inversions does it have?

My idea:
My initial thoughts was, if the array element is in sequence, doesn't it mean that the array is sorted and hence the inversion count is 0? If the array is sorted in descending order that inversion count is the maximum so the first element should have n-1 inversion, second is n-2 inversion all the way until the last element, 2 which have 1 inversion count. So I add up (n-1) + (n-2) + (n-3) +...+ 1 = n(n-1)/2. I would like to ask is this question asking any orders? Is my thinking correct? How should I solve it?

like image 705
user292965 Avatar asked Oct 19 '22 00:10

user292965


1 Answers

Yes, your reasoning is correct - the maximal number of inversions is obtained when the array is reverse sorted. You can prove it formally by induction (if you really want).

For an array with two elements, say, {1, 2}, check the two options.

For an array with n elements, the number of inversions can be divided to those attributed to the smallest element, and those attributed to the rest. By the induction hypothesis, the inversions attributed to the rest are obtained when the array (except for the last element, perhaps), is sorted in reverse order. The number of inversions attributed to the smallest element is the most when it is the last.

like image 122
Ami Tavory Avatar answered Oct 21 '22 05:10

Ami Tavory