1337. Weighted Inversion Distance
In a queue of n people with heights nums, a pair of positions i < j is out of order when nums[i] > nums[j], and the pair is as bad as the distance j - i between the two people. Return the sum of j - i over all out-of-order pairs, as a 64-bit integer. Equal heights are never out of order. The answer is guaranteed to be at most n^3 / 6, which fits in 53 bits. A merge sort that remembers the original positions solves it in O(n log n) time: when a right-half element at position j is placed while c left-half elements remain, with position sum S, add c * j - S.
Example 1
- Input:
- nums = [3,1,2]
- Output:
- 3
- Explanation:
The pairs (3, 1) at distance 1 and (3, 2) at distance 2 are out of order, giving 3.
Example 2
- Input:
- nums = [1,2,3,4]
- Output:
- 0
- Explanation:
The array is sorted, so no pair is out of order.
Example 3
- Input:
- nums = [4,3,2,1]
- Output:
- 10
- Explanation:
All six pairs are out of order: three at distance 1, two at distance 2 and one at distance 3, giving 3 + 4 + 3 = 10.
Constraints
1 ≤ n ≤ 105
-109 ≤ nums[i] ≤ 109
The answer is at most n^3 / 6, below 253
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)