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:
- Dynamic Programming on Trees | Set-1
- Bitmasking and Dynamic Programming | Set-2 (TSP)
- Dynamic Programming on Trees | Set 2
- Top 20 Dynamic Programming Interview Questions
- Number of Unique BST with a given key | Dynamic Programming
- Dynamic Programming vs Divide-and-Conquer
- Double Knapsack | Dynamic Programming
- Dynamic Programming | Building Bridges
- How to solve a Dynamic Programming Problem ?
- Greedy approach vs Dynamic programming
- Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
- Longest subsequence with a given OR value : Dynamic Programming Approach
- Overlapping Subproblems Property in Dynamic Programming | DP-1
- Optimal Substructure Property in Dynamic Programming | DP-2
- Understanding The Coin Change Problem With 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 firstname.lastname@example.org. 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.