codes, where codes[i] is the code of the i-th book; codes may repeat.
To put a book in its place, the neighbours on one side have to be shifted, and the librarian picks the side with less shifting. So the cost of inserting a book with code x is the smaller of two numbers: how many books already on the shelf have a code strictly less than x, and how many have a code strictly greater than x.
Return the total cost of placing all the books, modulo 10⁹ + 7.codes=[4, 8, 2, 6] → 1
4 goes onto the empty shelf: 0. For 8 there is one smaller book and no larger one: 0. For 2 nothing is smaller: 0. For 6 two are smaller (2 and 4) and one is larger (8): 1. The total is 1.
codes=[5, 5, 1, 9, 5, 3] → 2
The costs in order are 0, 0, 0, 0, 1 (for the third 5 one book is smaller and one larger), 1 (for 3 one is smaller and four are larger). Equal codes count as neither smaller nor larger. The total is 2.
codes=[7] → 0
codes=[4, 8, 2, 6]
1
Run checks the first 3 tests in your browser. Submit checks all 116 tests on the server, hidden ones included.