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