1370. Swap Cost Sort
A robot arm in a warehouse reorders crates standing in a row. The array nums holds the distinct positive weights of the crates. The arm can swap any two crates, wherever they stand, and one swap costs the sum of the two weights it moves.
Return the minimum total cost needed to arrange the crates so the weights are in strictly ascending order, as a long. Think of the permutation that sends each crate to its sorted place: it splits into cycles, and each cycle can be repaired either with its own lightest crate or by borrowing the globally lightest crate as a helper. Aim for O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [2,1,3]
- Output:
- 3
- Explanation:
One swap of the crates weighing 2 and 1 sorts the row and costs 2 + 1 = 3.
Example 2
- Input:
- nums = [1,2,3,4]
- Output:
- 0
- Explanation:
The row is already sorted, so the cost is 0.
Example 3
- Input:
- nums = [5,4,3,2,1]
- Output:
- 12
- Explanation:
Swap 5 with 1 (cost 6) and 4 with 2 (cost 6); the middle crate stays, for a total of 12.
Constraints
-
1 ≤ nums.length ≤ 105 -
all values in
numsare distinct -
1 ≤ nums[i] ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)