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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: A = 4, B = 0
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
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:
Time Complexity: O(1)
Auxiliary Space: O(1)