Given two integers N and M and the task is to convert N to M with the following operations:
- Multiply N by 2 i.e. N = N * 2.
- Subtract 1 from N i.e. N = N – 1.
Input: N = 4, M = 6
Perform operation 2: N = N – 1 = 4 – 1 = 3
Perform operation 1: N = N * 2 = 3 * 2 = 6
Input: N = 10, M = 1
Approach: Create an array dp of size MAX = 105 + 5 to store the answer in order to prevent same computation again and again and initialize all the array elements with -1.
- If N ≤ 0 or N ≥ MAX means it can not be converted to M so return MAX.
- If N = M then return 0 as N got converted to M.
- Else find the value at dp[N] if it is not -1, it means it has been calculated earlier so return dp[N].
- If it is -1 then will call the recursive function as 2 * N and N – 1 and return the the minimum because if N is odd then it can be reached only by performing N – 1 operations and if N is even then 2 * N opearations have to be performed so check both the possibililties and return the minimum.
Below is the implementation of the above approach:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Bitmasking and Dynamic Programming | Set-2 (TSP)
- Dynamic Programming on Trees | Set-1
- Dynamic Programming on Trees | Set 2
- Dynamic Programming vs Divide-and-Conquer
- Dynamic Programming | Building Bridges
- Top 20 Dynamic Programming Interview Questions
- Double Knapsack | Dynamic Programming
- How to solve a Dynamic Programming Problem ?
- Greedy approach vs Dynamic programming
- Ackermann's function using Dynamic programming
- Number of Unique BST with a given key | Dynamic Programming
- Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
- Longest subsequence with a given OR value : Dynamic Programming Approach
- Python | Implementing Dynamic programming using Dictionary
- Optimal Substructure Property in Dynamic Programming | DP-2
- Overlapping Subproblems Property in Dynamic Programming | DP-1
- Optimal Strategy for the Divisor game using Dynamic Programming
- Understanding The Coin Change Problem With Dynamic Programming
- Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
- Distinct palindromic sub-strings of the given string using Dynamic Programming
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.