Problem · Array
Minimum Swaps
Learn this problemProblem statement
You are given an array popularity containing the unique popularity ratings of n items.
The shopkeeper wants the items arranged from left to right in decreasing popularity.
- In one operation, the shopkeeper can swap any two items.
- Your task is to determine the minimum number of swaps needed to achieve the correct decreasing order.
Function
minimumSwaps(popularity: int[]) → intExamples
Example 1
popularity = [3, 4, 1, 2]return = 2Suppose there are n = 4 items, and popularity = [3, 4, 1, 2].
Output: 2
Explanation
- First swap: Switch items with ratings
3and4to get[4, 3, 1, 2]. - Second swap: Switch items with ratings
1and2to get[4, 3, 2, 1].
Constraints
1 ≤ n ≤ 2 × 10^51 ≤ popularity[i] ≤ n- Test Case Input Format
- The first line contains the integer
n. - The next
nlines contain an integer element ofpopularity[i].
- The first line contains the integer