Minimum moves

You want to reach a destination but you decide that you can make moves in two directions only. If you are in a position (x, y), then you can move to (x+1, y+1) or (x+1, y). You must start your journey from (0, 0) and your destination is (X, Y). Your task is to find the minimum number of moves that you require to reach the destination or if he cannot reach the destination.

Example:

Input:  x = 1, y = 0
Output: 1

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int minMoves(int xint y)
{
    if (x < 0 || y < 0)
        return -1;
    else if (x == 0 && y != 0)
        return -1;
    else if (y == 0)
        return x;
    else
    {
        if (y > x)
            return -1;
        else
        {
            int res = min(xy);
            res += x - y;
            return res;
        }
    }
}
int main()
{

    int x = 1y = 0;

    cout << minMoves(xy);

    return 0;
}


No comments:

Post a Comment