A short freight train has n cargo cars lined up and numbered 0 to n-1 from the front. Car i is carrying a load rated loads[i] (ratings may repeat across cars). The yard crew can only ever swap two cars that are directly next to each other, one swap at a time. The train is considered properly marshalled once both of the following hold: the car now at position 0 has a load rating equal to the overall maximum rating among all cars, and the car now at position n-1 has a load rating equal to the overall minimum rating among all cars. (When every car shares the same rating, both conditions are already satisfied and no swaps are needed.) Determine the minimum number of adjacent swaps the crew must perform to reach a properly marshalled arrangement.
n, the number of cargo cars.n space-separated integers loads[0], ..., loads[n-1].Print a single integer: the minimum number of adjacent swaps required.
Example 1
Input
5 3 7 5 2 7
Expected
2
Explanation
With loads = [3, 7, 5, 2, 7], the maximum rating is 7 (first appearing at position 1) and the minimum rating is 2 (appearing only at position 3). Moving the car at position 1 to the front costs 1 swap, and moving the car at position 3 to the back (position 4) costs 1 swap. Since the max car (position 1) starts to the left of the min car (position 3), their paths never cross, so no swap is shared: total = 1 + 1 = 2.
Example 2
Input
3 2 9 4
Expected
2
Explanation
With loads = [2, 9, 4], the maximum rating is 9 (at position 1) and the minimum rating is 2 (at position 0). Moving the max car to the front costs 1 swap, and moving the min car to the back (position 2) costs 2 swaps. But here the max car starts to the right of the min car, so one swap can do double duty: swapping positions 0 and 1 directly moves the max car one step toward the front and the min car one step toward the back at the same time. That shared swap is counted once instead of twice, so the total is 1 + 2 - 1 = 2 rather than 3.
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 →