← 返回 jpmorgan 的题目列表Minimum Swaps to Sort Descending
类型:qbank
Given an array, compute the minimum number of swaps needed to sort it in decreasing order.
Requirements
Input: an array of integers.
Return the minimum number of swaps required to reorder it into descending order.
Clarify duplicate handling. If duplicates exist, stable target positions or value-index pairs are needed to avoid ambiguous swaps.
Notes
Sort value-index pairs by value descending to compute each element's target position, then count cycles in the permutation.
Each cycle of length k contributes k - 1 swaps.
If all values are distinct, the implementation is straightforward. If duplicates are allowed, pair each value with its original index to make target positions deterministic.
Preparation
Implement cycle counting from a target-position permutation.
Test already-sorted descending input, ascending input, duplicates, and a single long cycle.