Replace for X codechef October long challenge solution -
This Problem is taken from CodeChef October long challenge.
2 5 4 3 4 4 9 7 0 8 2 25 1 2 100 20
read More-Positive AND Codehef October long challenge Solution |CodeChef October long challenge editorial
read more-Covid Run Codechef October long challenge problem solution| Codechef October long challenge problem solution
Since a note is mentioned in question that
Note: the k-th smallest number in an array is the k-th number from the left when the array is sorted in non-decreasing order.
So first of all we will sort our array/vector in non-decreasing order so that we can find kth smalles number.
because index is starting from 0 in my code so i did previous step.
I have written a solution function which return minumum number of operation reequired.
Now Let's jump into logic.
1-first of all i will check is(v[p]==X) if it is true i will simply return 0 because in this case i already have my answer.
2-now i will maintain a count variable which count total operation required.
3-Main logic start from here since out array is sorted till now so we have three choices from here if(k>p),if(k<p) and if(k==p) and
in every 3 case these 3 case also contain two-two cases if(v[p]<x) and if(v[p]>x).
4- if(k>p) and if(v[p]<x) in this case we never reach to final solution so i will return -1 in this case.
if (k>p) && v[p]> x in this case i can reach to my solution and i will try to add some smaller value at k so that i can shift
value at p toward k ans every time i increase my value by one.
5- same if (k<p) this case is totally opposite of case 4.
6- if (k==p)
in this case i can reach to my solution
if(v[p]>x) i have to shift pth value to left
and if(v[p]<x) i will shift pth value to right
and count ans.
finllay i return ans which tells minimum way to get final solution.
code of this problem