- Related Questions & Answers
- Program to Find Out the Number of Moves to Reach the Finish Line in Python
- Program to find minimum number of buses required to reach final target in python
- Program to find minimum steps to reach target position by a chess knight in Python
- Minimum Knight Moves in C++
- Minimum Moves to Equal Array Elements in C++
- Program to find number of given operations required to reach Target in Python
- Program to find number of combinations of coins to reach target in Python
- Find minimum steps required to reach the end of a matrix in C++
- Find the minimum number of steps to reach M from N in C++
- Find the minimum cost to reach destination using a train
- Minimum Initial Points to Reach Destination
- Program to check robot can reach target by keep moving on visited spots in Python
- How to create an infinite loop in C#?
- Count minimum number of “move-to-front” moves to sort an array in C++
- Word Ladder (Length of shortest chain to reach a target word) in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a number position in infinite number line. (-inf to +inf). Starting from 0, we have to reach to the target by moving as described. In ith move, we can go i steps either left or right. We have to find minimum number of moves that are required. Suppose the target is 2, so minimum steps will be 3. From 0 to 1, from 1 to -1 and from -1 to 2.

To solve this problem, we have some important points to remember. If the target is negative, then just take this as positive, as the number line is identical. For solving, the idea is move in one direction as long as possible. So from 0 go to 1, from 1 go to 3 (1 + 2), from 3 go to 6(1 + 2 + 3) and so on. Thus if after nth move the target is found, then simply return the number of moves. But if the founded point is greater than target, then we have to find the difference between how much we are ahead. Now we can see, if we move ith step backward, then the sum will be (sum – 2i). Now if sum-2i is the target, then we have got the result. But the difference can be even or odd. For even, return n as result, otherwise, we take one more step. So add n + 1 to sum and now again take the difference. If n + 1 is target, then return, otherwise do one more step with n + 2.

#include<iostream> #include<cmath> using namespace std; int minStepToTarget(int target) { target = abs(target); int sum = 0, min_step = 0; while (sum < target || (sum - target) % 2 != 0) { min_step++; sum += min_step; } return min_step; } int main() { int target = 11; cout << "Minimum step to reach the target is: " << minStepToTarget(target); }

Minimum step to reach the target is: 5

Advertisements