Given integers N, P and Q where N denotes the destination position. The task is to move from position 0 to position N with minimum cost possible and print the calculated cost. All valid movements are:
- From position X you can go to position X + 1 with a cost of P
- Or, you can go to the position 2 * X with a cost of Q
Input: N = 1, P = 3, Q = 4
Move from position 0 to 1st position with cost = 3.
Input: N = 9, P = 5, Q = 1
Move from position 0 to 1st position with cost = 5,
then 1st to 2nd with cost = 1,
then 2nd to 4th with cost = 1,
then 4th to 8th with cost = 1,
finally 8th to 9th with cost = 5.
Total cost = 5 + 1 + 1 + 1 + 5 = 13.
Approach: Instead of going from beginning to destination we can start moving from the destination to initial position and keep track of the cost of jumps.
- If N is odd then the only valid move that could lead us here is N-1 to N with a cost of P.
- If N is even then we calculate cost of going from N to N/2 position with both the moves and take the minimum of them.
- When N equals 0, we return our total calculated cost.
Below is the implementation of above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Minimum cost to reach end of array array when a maximum jump of K index is allowed
- Minimum Cost Path with Left, Right, Bottom and Up moves allowed
- Find the minimum cost to reach destination using a train
- Minimum cost to reach the top of the floor by climbing stairs
- Minimum cost to convert str1 to str2 with the given operations
- Minimum cost to sort strings using reversal operations of different costs
- Minimum Cost to make all array elements equal using given operations
- Minimum cost for acquiring all coins with k extra coins allowed with every coin
- Minimum time to reach a point with +t and -t moves at time t
- Minimize Cost with Replacement with other allowed
- Sum of cost of all paths to reach a given cell in a Matrix
- Counts paths from a point to reach Origin
- Number of steps required to reach point (x,y) from (0,0) using zig-zag way
- Counts paths from a point to reach Origin : Memory Optimized
- Minimize cost to convert given two integers to zero using given operations
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.