![]() |
VOOZH | about |
You are given two positive integers x and y. In one operation, you can do one of the four following operations:
Return the minimum number of operations required to make x and y equal.
Examples:
Input: x = 26, y = 1
Output: 3
Explanation: We can make 26 equal to 1 by applying the following operations:
- Decrement x by 1
- Divide x by 5
- Divide x by 5
It can be shown that 3 is the minimum number of operations required to make 26 equal to 1.
Input: x = 54, y = 2
Output: 4
Explanation: We can make 54 equal to 2 by applying the following operations:
- Increment x by 1
- Divide x by 11
- Divide x by 5
- Increment x by 1
It can be shown that 4 is the minimum number of operations required to make 54 equal to 2.
Approach:
We need to check for 5 ways in our recursive calls :
- Just abs diff of x & y can be ans. So initialise res = abs(x - y)
- We may go to multiple of 5 which is smaller than x. This can be achieved by just subtracting x%5 from x and divide x by 5. Here total operations = x%5 ( this many time decreament ) + 1( for division by 5).
- We may go to multiple of 5 which is larger than x. This can be achieved by just adding (5 - x%5) to x and then divid x by 5. Here total operations = 5 - x%5 ( this many time increment ) + 1( for division by 5).
- We may go to multiple of 11 which is smaller than x. This can be achieved by just subtracting x%11 from x and divide x by 11. Here total operations = x%11 ( this many time decreament ) + 1( for division by 11).
- We may go to multiple of 11 which is larger than x. This can be achieved by just adding (11 - x%11) to x and then divid x by 11. Here total operations = 11 - x%11 ( this many time increment ) + 1( for division by 11).
- With considereing above cases we need to write recursive code to find the min operations.
Step-by-step algorithm:
Below is the implementation of the algorithm:
Minimum operations to make 26 and 1 equal: 3
Time Complexity: O(N)
Auxiliary Space: O(N)