3644. Maximum K to Sort a Permutation Medium
1/**
2 * [3644] Maximum K to Sort a Permutation
3 *
4 * You are given an integer array nums of length n, where nums is a <span data-keyword="permutation-array">permutation</span> of the numbers in the range [0..n - 1].
5 * You may swap elements at indices i and j only if nums[i] AND nums[j] == k, where AND denotes the bitwise AND operation and k is a non-negative integer.
6 * Return the maximum value of k such that the array can be sorted in non-decreasing order using any number of such swaps. If nums is already sorted, return 0.
7 *
8 * <strong class="example">Example 1:
9 * <div class="example-block">
10 * Input: <span class="example-io">nums = [0,3,2,1]</span>
11 * Output: <span class="example-io">1</span>
12 * Explanation:
13 * Choose k = 1. Swapping nums[1] = 3 and nums[3] = 1 is allowed since nums[1] AND nums[3] == 1, resulting in a sorted permutation: [0, 1, 2, 3].
14 * </div>
15 * <strong class="example">Example 2:
16 * <div class="example-block">
17 * Input: <span class="example-io">nums = [0,1,3,2]</span>
18 * Output: <span class="example-io">2</span>
19 * Explanation:
20 * Choose k = 2. Swapping nums[2] = 3 and nums[3] = 2 is allowed since nums[2] AND nums[3] == 2, resulting in a sorted permutation: [0, 1, 2, 3].
21 * </div>
22 * <strong class="example">Example 3:
23 * <div class="example-block">
24 * Input: <span class="example-io">nums = [3,2,1,0]</span>
25 * Output: <span class="example-io">0</span>
26 * Explanation:
27 * Only k = 0 allows sorting since no greater k allows the required swaps where nums[i] AND nums[j] == k.
28 * </div>
29 *
30 * Constraints:
31 *
32 * 1 <= n == nums.length <= 10^5
33 * 0 <= nums[i] <= n - 1
34 * nums is a permutation of integers from 0 to n - 1.
35 *
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/maximum-k-to-sort-a-permutation/
40// discuss: https://leetcode.com/problems/maximum-k-to-sort-a-permutation/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45 pub fn sort_permutation(nums: Vec<i32>) -> i32 {
46 0
47 }
48}
49
50// submission codes end
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn test_3644() {
58 }
59}
60Back
© 2026 bowen.ge All Rights Reserved.