3587. Minimum Adjacent Swaps to Alternate Parity Medium
1/**
2 * [3587] Minimum Adjacent Swaps to Alternate Parity
3 *
4 * You are given an array nums of distinct integers.
5 * In one operation, you can swap any two adjacent elements in the array.
6 * An arrangement of the array is considered valid if the parity of adjacent elements alternates, meaning every pair of neighboring elements consists of one even and one odd number.
7 * Return the minimum number of adjacent swaps required to transform nums into any valid arrangement.
8 * If it is impossible to rearrange nums such that no two adjacent elements have the same parity, return -1.
9 *
10 * <strong class="example">Example 1:
11 * <div class="example-block">
12 * Input: <span class="example-io">nums = [2,4,6,5,7]</span>
13 * Output: <span class="example-io">3</span>
14 * Explanation:
15 * Swapping 5 and 6, the array becomes [2,4,5,6,7]
16 * Swapping 5 and 4, the array becomes [2,5,4,6,7]
17 * Swapping 6 and 7, the array becomes [2,5,4,7,6]. The array is now a valid arrangement. Thus, the answer is 3.
18 * </div>
19 * <strong class="example">Example 2:
20 * <div class="example-block">
21 * Input: <span class="example-io">nums = [2,4,5,7]</span>
22 * Output: <span class="example-io">1</span>
23 * Explanation:
24 * By swapping 4 and 5, the array becomes [2,5,4,7], which is a valid arrangement. Thus, the answer is 1.
25 * </div>
26 * <strong class="example">Example 3:
27 * <div class="example-block">
28 * Input: <span class="example-io">nums = [1,2,3]</span>
29 * Output: <span class="example-io">0</span>
30 * Explanation:
31 * The array is already a valid arrangement. Thus, no operations are needed.
32 * </div>
33 * <strong class="example">Example 4:
34 * <div class="example-block">
35 * Input: <span class="example-io">nums = [4,5,6,8]</span>
36 * Output: <span class="example-io">-1</span>
37 * Explanation:
38 * No valid arrangement is possible. Thus, the answer is -1.
39 * </div>
40 *
41 * Constraints:
42 *
43 * 1 <= nums.length <= 10^5
44 * 1 <= nums[i] <= 10^9
45 * All elements in nums are distinct.
46 *
47 */
48pub struct Solution {}
49
50// problem: https://leetcode.com/problems/minimum-adjacent-swaps-to-alternate-parity/
51// discuss: https://leetcode.com/problems/minimum-adjacent-swaps-to-alternate-parity/discuss/?currentPage=1&orderBy=most_votes&query=
52
53// submission codes start here
54
55impl Solution {
56 pub fn min_swaps(nums: Vec<i32>) -> i32 {
57 0
58 }
59}
60
61// submission codes end
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn test_3587() {
69 }
70}
71Back
© 2026 bowen.ge All Rights Reserved.