Sunday, February 15, 2026

Minimum moves - reach the destination X, Y (Easy)

Index of "Algorithms: Design and Analysis"
<<< Previous    Next >>>

Problem
You want to reach a destination but you decide that you can make moves in two directions only. If you are at 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.

Input format

The first line contains an integer 
 denoting the number of test cases.
For each test case, there is a single line consisting of two integers 
 and 
.
Output format

For each test case, print a single line denoting the minimum number of moves that you must take to reach the destination. Print -1 if you cannot reach the destination.

Constraints



Sample Input
1
1 0
Sample Output
1
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation
He can take step from (x,y) to (x+1,y) .

So he can take step from (0,0) to (1,0).

Number of moves is 1 and is the optimal solution

My Code


def solve(X, Y):
    if X < 0 or Y < 0 or Y > X:
        return -1
    else:
        return X
    

T = int(input())

for _ in range(T):
    X, Y = map(int, input().split())
    print(solve(X, Y))

ChatGPT's Code


t = int(input())

for _ in range(t):
    X, Y = map(int, input().split())
    
    if X < 0 or Y < 0 or Y > X:
        print(-1)
    else:
        print(X)

No comments:

Post a Comment