![]() |
VOOZH | about |
Given a permutation of N elements (Elements are in range 0 to N-1). A fixed point is an index at which the value is same as the index (That is, a[i]=i). You are allowed to make atmost 1 swap. Find the maximum number of fixed points that you can get.
Examples:
Input : N = 5
arr[] = {0, 1, 3, 4, 2}
Output : 3
2 and 3 can be swapped to get:
0 1 2 4 3
which has 3 fixed points.
Input : N = 5
a[] = {0, 1, 2, 4, 3}
Output : 5
Since we are allowed to make only 1 swap, the number of fixed points can be increased by atmost 2.
Let's have an array pos which keeps the position of each element in the input array. Now, we traverse the array and have the following cases:
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.
Below is the implementation of the above approach:
3
Time Complexity: O(N)