error
*********************unlock
hello @ayu2321
why r u running this loop.
see in total u r allowed to make k operation .
try to thing of a greedy approach .
i hav not done greedy algorithms yet
there nothing to study in greedy.
you just have to think like a greedy.
The following problem can be easily solved by using hashmap or unordered map. The hint to solve the problem is that the given array will always contain permutation of the first N natural numbers. So we will prepare a map which will contain element as the key and the index at which it is present as the value.
- Create the map by filling the number as the key and the index at which it is present as the value
- Iterate over the whole array.
- For element at a particular index m we will check if it is present at its best spot or not.
- The best spot of any number num is the N-num index of the array.
- If the number is not present at its best spot then we will swap the number with element present at that spot.
- As we have stored the index of every element in the map we can easily retrieve that from the map to get the swap done.
https://ide.codingblocks.com/s/279676
sir in ur code u hav done that if(v[i]==x)then it is at its correct position…but how can u compare an element with a position as v[i] is storing an element and x is storing the best position
no x is not storing position.
it is storing best value for index i.
and that is why
x=n-i.
for i=0 , x=n that is for 0th position best value is n.
similarly for other values of i.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.