You want to reach a destination but you decide that you can make moves in two directions only. If you are in a position , then you can move to or . You must start your journey from and your destination is . 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 x, int 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(x, y);res += x - y;return res;}}}int main(){int x = 1, y = 0;cout << minMoves(x, y);return 0;}
No comments:
Post a Comment