Minimize jumps to reach X by jumping K positions or 1 position
Last Updated :
22 Aug, 2022
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.
Example:
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:
C++
#include <bits/stdc++.h>
using namespace std;
int findJumps( int X, int K)
{
int div1 = X / K;
int div2 = X / K + 1;
int N = div1 * K, M = div2 * K;
int S1 = div1 + (X - N);
int S2 = div2 + (M - X);
return min(S1, S2);
}
int main()
{
int X = 5, K = 2;
cout << findJumps(X, K);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static int findJumps( int X, int K)
{
int div1 = X / K;
int div2 = X / K + 1 ;
int N = div1 * K, M = div2 * K;
int S1 = div1 + (X - N);
int S2 = div2 + (M - X);
return Math.min(S1, S2);
}
public static void main(String[] args)
{
int X = 5 , K = 2 ;
System.out.println(findJumps(X, K));
}
}
|
Python3
def findJumps(X, K) :
div1 = int (X / K)
div2 = int (X / K) + 1
N = div1 * K; M = div2 * K;
S1 = div1 + (X - N)
S2 = div2 + (M - X)
return min (S1, S2)
if __name__ = = "__main__" :
X = 5 ; K = 2 ;
print (findJumps(X, K))
|
C#
using System;
public class GFG
{
public static int findJumps( int X, int K)
{
int div1 = X / K;
int div2 = X / K + 1;
int N = div1 * K, M = div2 * K;
int S1 = div1 + (X - N);
int S2 = div2 + (M - X);
return Math.Min(S1, S2);
}
public static void Main( string [] args)
{
int X = 5, K = 2;
Console.WriteLine(findJumps(X, K));
}
}
|
Javascript
<script>
function findJumps(X, K)
{
let div1 = Math.floor( X / K);
let div2 = Math.floor(X / K + 1);
let N = div1 * K, M = div2 * K;
let S1 = div1 + (X - N);
let S2 = div2 + (M - X);
return Math.min(S1, S2);
}
let X = 5;
let K = 2;
document.write(findJumps(X, K));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...