A shuffled manuscript lists n page numbers in the order the pages were stacked. Two pages form an out-of-order pair if the page that appears earlier in the stack carries a strictly larger number than a page that appears later. Counting these pairs measures how far the stack is from sorted.
Count the number of pairs (i, j) with i < j (by stack position) and page[i] > page[j]. Page numbers may repeat; only strictly-greater pairs count. The intended approach counts these pairs while performing a merge sort.
Line 1: an integer n, the number of pages.
Line 2: n space-separated integers, the page numbers in stack order.
A single integer: the number of out-of-order pairs.
Example 1
Input
5 2 4 1 3 5
Expected
3
Explanation
The out-of-order pairs are (2,1), (4,1) and (4,3), so there are 3.
Example 2
Input
4 1 2 3 4
Expected
0
Explanation
The pages are already increasing, so there are no out-of-order pairs.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →