Minimize moves to make X and Y equal using given subtraction operations
Last Updated :
06 May, 2022
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.
Examples:
Input: X = 4, Y = 7
Output: 1
Explanation: Select Z = 3, then the new X will be 4 + 3 = 7.
Hence, it requires only one operation.
Input: X = 6, Y = 6
Output: 0
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 :
C++
#include <bits/stdc++.h>
using namespace std;
int minMoves( int X, int Y)
{
if (X == Y) {
return 0;
}
else if (X > Y && (X - Y) % 2 == 0) {
return 1;
}
else if (X < Y && (Y - X) % 2 == 1) {
return 1;
}
else {
return 2;
}
}
int main()
{
int X = 4, Y = 7;
cout << minMoves(X, Y);
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static int minMoves( int X, int Y)
{
if (X == Y) {
return 0 ;
}
else if (X > Y && (X - Y) % 2 == 0 ) {
return 1 ;
}
else if (X < Y && (Y - X) % 2 == 1 ) {
return 1 ;
}
else {
return 2 ;
}
}
public static void main(String[] args)
{
int X = 4 , Y = 7 ;
System.out.print(minMoves(X, Y));
}
}
|
Python3
def minMoves(X, Y):
if (X = = Y):
return 0
elif (X > Y and (X - Y) % 2 = = 0 ):
return 1
elif (X < Y and (Y - X) % 2 = = 1 ):
return 1
else :
return 2
X, Y = 4 , 7
print (minMoves(X, Y))
|
C#
using System;
class GFG {
static int minMoves( int X, int Y)
{
if (X == Y) {
return 0;
}
else if (X > Y && (X - Y) % 2 == 0) {
return 1;
}
else if (X < Y && (Y - X) % 2 == 1) {
return 1;
}
else {
return 2;
}
}
public static void Main()
{
int X = 4, Y = 7;
Console.Write(minMoves(X, Y));
}
}
|
Javascript
<script>
const minMoves = (X, Y) => {
if (X == Y) {
return 0;
}
else if (X > Y && (X - Y) % 2 == 0) {
return 1;
}
else if (X < Y && (Y - X) % 2 == 1) {
return 1;
}
else {
return 2;
}
}
let X = 4, Y = 7;
document.write(minMoves(X, Y));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...