Maximize jump size to reach all given points from given starting point
Given an array, arr[] consisting of N integers representing coordinates on a number line and an integer S. Find the maximum size of jump required to visit all the coordinates at least once if the starting position is S. Also, Jumping in both directions is permitted.
Example:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input: arr[]={1, 7, 3, 9, 5, 11}, S=3
Output: 2
Explanation: Jumps of size 2 is able to visit all the coordinates on the line, in the following way:
Jump -2: Reach 1 from 3.
Jump +2: Reach 3 from 1.
Jump +2: Reach 5 from 3.
Jump +2: Reach 7 from 5.
Jump +2: Reach 9 from 7.
Jump +2: Reach 11 from 9.Input: arr[]={33, 105, 57}, S=81
Output: 24
Approach: An observation can be made after reading the problem, that the greatest common divisor of all the differences between two adjacent points on the line is the maximum size of Jump needed to visit all points. So, to solve this problem, follow the below steps:
- Insert S, in the array arr, then sort it.
- Find the gcd between the differences of all adjacent pairs in the array arr.
- Return the final gcd as the answer to this problem.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum size of jump// to reach all the coordinatesint minJumpSize(vector<int>& arr, int S){ // Pushing S into the line arr.push_back(S); // Sorting arr, to get coordinates in // a sorted way sort(arr.begin(), arr.end()); // Finding gcd between the differences of // all adjacent pairs int gcd = arr[1] - arr[0]; for (int i = 1; i < arr.size(); i++) { gcd = __gcd(gcd, __gcd(gcd, arr[i] - arr[i - 1])); } return gcd;} // Driver Codeint main(){ vector<int> arr = { 1, 7, 3, 9, 5, 11 }; int S = 3; cout << minJumpSize(arr, S);} |
2
Time Complexity: O(NlogN)
Auxiliary Space: O(1).

