Convert A into B by incrementing or decrementing 1, 2, or 5 any number of times
Given two integers A and B, the task is to find the minimum number of moves needed to make A equal to B by incrementing or decrementing the A by either 1, 2, or 5 any number of times.
Examples:
Input: A = 4, B = 0
Output: 2
Explanation:
Perform the operation as follows:
- Decreasing the value of A by 2, modifies the value of A to (4 – 2) = 2.
- Decreasing the value of A by 2 modifies the value of A to (2 – 2) = 0. Which is equal to B.
Therefore, the number of moves required is 2.
Input: A = 3, B = 9
Output: 2
Approach: The given problem can be solved by using the Greedy Approach. The idea is to first find the increment or decrements of 5, then 2, and then 1 is needed to convert A to B. Follow the steps below to solve the problem:
- Update the value of A as the absolute difference between A and B.
- Now, print the value of (A/5) + (A%5)/2 + (A%5)%2 as the minimum number of increments or decrements of 1, 2, or 5 to convert A into B.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumSteps( int a, int b)
{
int cnt = 0;
a = abs (a - b);
cnt = (a / 5) + (a % 5) / 2 + (a % 5) % 2;
return cnt;
}
int main()
{
int A = 3, B = 9;
cout << minimumSteps(A, B);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int minimumSteps( int a, int b)
{
int cnt = 0 ;
a = Math.abs(a - b);
cnt = (a / 5 ) + (a % 5 ) / 2 + (a % 5 ) % 2 ;
return cnt;
}
public static void main(String[] args)
{
int A = 3 , B = 9 ;
System.out.println(minimumSteps(A, B));
}
}
|
Python3
def minimumSteps(a, b):
cnt = 0
a = abs (a - b)
cnt = (a / / 5 ) + (a % 5 ) / / 2 + (a % 5 ) % 2
return cnt
A = 3
B = 9
print (minimumSteps(A, B))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int minimumSteps( int a, int b)
{
int cnt = 0;
a = Math.Abs(a - b);
cnt = (a / 5) + (a % 5) / 2 + (a % 5) % 2;
return cnt;
}
public static void Main()
{
int A = 3, B = 9;
Console.Write(minimumSteps(A, B));
}
}
|
Javascript
<script>
function minimumSteps(a, b)
{
let cnt = 0;
a = Math.abs(a - b);
cnt = Math.floor(a / 5) + Math.floor((a % 5) / 2) + (a % 5) % 2;
return cnt;
}
let A = 3, B = 9;
document.write(minimumSteps(A, B));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
23 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...