heights. In one step you may swap two **neighbouring** students.
The photographer wants the shortest student at the left end and the tallest at the right end. If several students share the smallest or the largest height, any one of them may take that end. The order of everyone else does not matter.
Return the minimum number of swaps needed.heights=[4, 7, 2, 7, 5] → 3
Move the 2 to the front in 2 swaps: [2, 4, 7, 7, 5]. Then the last 7 to the end in 1 swap: [2, 4, 7, 5, 7]. 3 in total.
heights=[3, 1] → 1
One swap gives [1, 3]: the minimum is on the left and the maximum on the right.
heights=[5, 5, 5] → 0
All values are equal, so each is both a smallest and a largest one. No swaps are needed.
heights.length ≤ 10⁵heights[i] ≤ 10⁵heights=[4, 7, 2, 7, 5]
3
Run checks the first 3 tests in your browser. Submit checks all 108 tests on the server, hidden ones included.