Minimize moves to make X and Y equal using given subtraction operations
Given two positive integers, X and Y, the task is to find the minimum number of operations to make X and y equal where in one operation, we can select any positive integer Z and do the following process.
- If the number Z is even, subtract Z from X.
- If the number Z is odd, add Z to X.
Input: X = 4, Y = 7
Explanation: Select Z = 3, then the new X will be 4 + 3 = 7.
Hence, it requires only one operation.
Input: X = 6, Y = 6
Explanation: Both of them are already the same.
Hence, it requires 0 operations.
Approach: This problem can be solved using the Greedy approach based on the following observation:
There are only three possible answers:
- First, if X = Y, no operation is required,
- Second, If X > Y and X − Y is even or X < Y and Y − X is odd, then only 1 operation is required.
- Third, if X > Y and X − Y is odd or X < Y and Y − X is even, then there is need for 2 operations. One move extra is required for turning it to the second case
Follow the below steps to solve this problem:
- Find the relation between X and Y.
- Now based on the relation find how many moves are needed based on the above observation.
Below is the implementation of the above approach :
Time Complexity: O(1)
Auxiliary Space: O(1)