[LeetCode] Maximum K to Sort a Permutation

3644. Maximum K to Sort a Permutation

You are given an integer array nums of length n, where nums is a permutation of the numbers in the range [0..n - 1].

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.

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int sortPermutation(vector<int>& nums) {
int res = INT_MAX, n = nums.size();
for(int i = 0; i < n; i++) {
if(nums[i] != i) {
res &= i;
}
}
return res == INT_MAX ? 0 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/08/17/PS/LeetCode/maximum-k-to-sort-a-permutation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.