Maximum number of fixed points using at most 1 swaps in C++

Problem statement

Given a permutation of N elements from 0 to N-1. A fixed point is an index at which the value is same as the index i.e. arr[i] = i. You are allowed to make at most 1 swap. Find the maximum number of fixed points that you can get.

Example

If input array is {0, 1, 2, 3, 4, 6, 5} then answer is 7.

• To adjust fixed point, we have to swap 6 and 5
• After this entire array becomes fixed point and maximum value of fixed point is 7.

Algorithm

• Create an array pos which keeps the position of each element in the input array
• Now, we traverse the array and have the following cases −
• If, a[i] = i. We can simply increment the count and move on
• If, pos[i] = a[i] which means that swapping the 2 terms would make i and a[i] fixed points, hence increasing the count by 2. Keep in mind that swap can be done at most once.
• At the end of the traversal, if we haven’t made any swap, it means that our swap was not able to increase count by 2, so now if there are at least 2 elements which are not fixed points, we can make a swap to increase count by 1, i.e. make one of those points a fixed point.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaximumFixedPoints(int arr[], int n) {
int i, pos[n], count = 0, swapped = 0;
for (i = 0; i < n; i++)
pos[arr[i]] = i;
for (i = 0; i < n; i++) {
if (arr[i] == i) {
count++;
} else if (swapped == 0 && pos[i] == arr[i]) {
count += 2;
swapped = 1;
}
}
if (swapped == 0 && count < n - 1) {
count++;
}
return count;
}
int main() {
int arr[] = {0, 1, 2, 3, 4, 6, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum value of fixed point = " << getMaximumFixedPoints(arr, n) << endl;
return 0;
}

Output

When you compile and execute above program. It generates following output −

Maximum edges = 7