Given two values X and K, the task is to minimize the number of jumps to reach X from 0 by jumping K positions or 1 position at a time.
Input: N = 5, K = 2 Output: 3 Explanation: First two jumps of K = 2 steps and third jump of 1 step will be required
Input: N = 3, K = 5 Output: 3 Explanation: First two jumps of 1 step will be required and the third jump will be of 3 positions. Or Use two jumps of 3 positions to reach 6 and then jump 1 position on left to reach 5
Approach: The problem can be solved based on the following mathematical idea:
To minimize the steps, it is optimal to cover as much distance as possible using jumps of K positions. Say N and M are the two multiples of K that are closest to X (N ≤ X and M > X).
So steps required to reach X can be:
S1 = N/K + (X – N)
S2 = M/K + (M – X)
The minimum number of steps = minimum between S1 and S2
Follow the steps mentioned below to solve the problem:
Get the values S1 and S2.
Find the minimum between them.
Return the minimum value as the answer.
Below is the implementation for the above approach:
Please Login to comment...