Given three integers N, K and M representing the Number of boxes (aligned horizontally from 1 to N), total numbers of allowed jumps and total available coins respectively, the task is to print the path that can be traversed within [1, N] by using exactly M coins in exactly K jumps. If a jump is made from position X to position Y then abs(X – Y) coins are used. If it is not possible to use M coins in K jumps, then print -1.
Input : N = 5, K = 4, M = 12
Output : 5 1 4 5
First jump: Box 1 -> Box 5. Hence, |1-5| = 4 coins used.
Second Jump: Box 5 -> Box 1 Hence, |5-1| = 4 coins used.
Third Jump: Box 1 -> Box 4 using 3 coins.
Fourth Jump: Box 4 -> Box 5 using 1 coin.
Hence, exactly 12 coins used in 4 jumps.
Input : N = 4, K = 3, M = 10
Output : -1
We can observe that the answer will be -1 for the following two cases:
- K > N-1 or
- K * (N-1) < M.
The problem can be solved using Greedy Approach following the steps given below:
Repeat the below operation until K become zero.
- Find the minimum of N-1 and M – K – 1.
- Based on the above minimum value, move towards the left or right based on the availability reduce K.
- Repeat the above steps until K becomes 0.
Below is implementation of the above approach:
5 1 4 5
Time Complexity: O(K)
Auxillary Space: O(1)
- Source to destination in 2-D path with fixed sized jumps
- Minimum cost for acquiring all coins with k extra coins allowed with every coin
- Check if given coins can be used to pay a value of S
- Check if it is possible to move from (a, 0) to (b, 0) with given jumps
- Burst Balloon to maximize coins
- Buy minimum items without change and given coins
- Reach the numbers by making jumps of two given lengths
- Greedy Algorithm to find Minimum number of Coins
- Minimum number of coins that can generate all the values in the given range
- Minimum jumps required to group all 1s together in a given Binary string
- Check if it is possible to reach a number by making jumps of two given length
- Traversal of tree with k jumps allowed between nodes of same height
- Probability of getting two consecutive heads after choosing a random coin among two different types of coins
- Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps
- Find the number of jumps to reach X in the number line from zero
- Shortest path on a Square
- Check if two nodes are on same path in a tree | Set 2
- Shortest path in a complement graph
- Maximum XOR path of a Binary Tree
- Path with maximum product in 2-d array