http://www.geeksforgeeks.org/minimum-distance-travel-cover-intervals/
Given many intervals as ranges and our position. We need to find minimum distance to travel to reach such a point which covers all the intervals at once.
Given many intervals as ranges and our position. We need to find minimum distance to travel to reach such a point which covers all the intervals at once.
We can solve this problem by concentrating only on endpoints. Since the requirement is to cover all intervals by reaching a point, all intervals must a share a point for answer to exist. Even the interval with leftmost end point must overlap with the interval right most start point.
First, we find right most start point and left most end point from all intervals. Then we can compare our position with these points to get the result which is explained below :
- If this right most start point is to the right of left most end point then it is not possible to cover all intervals simultaneously. (as in example 2)
- If our position is in mid between to right most start and left most end then there is no need to travel and all intervals will be covered by current position only (as in example 3)
- If our position is left to both points then we need to travel up to the rightmost start point and if our position is right to both points then we need to travel up to leftmost end point.
int
minDistanceToCoverIntervals(Interval intervals[],
int
N,
int
x)
{
int
rightMostStart = INT_MIN;
int
leftMostEnd = INT_MAX;
// looping over all intervals to get right most
// start and left most end
for
(
int
i = 0; i < N; i++)
{
if
(rightMostStart < intervals[i].start)
rightMostStart = intervals[i].start;
if
(leftMostEnd > intervals[i].end)
leftMostEnd = intervals[i].end;
}
int
res;
/* if rightmost start > leftmost end then all
intervals are not aligned and it is not
possible to cover all of them */
if
(rightMostStart > leftMostEnd)
res = -1;
// if x is in between rightmoststart and
// leftmostend then no need to travel any distance
else
if
(rightMostStart <= x && x <= leftMostEnd)
res = 0;
// choose minimum according to current position x
else
res = (x < rightMostStart) ? (rightMostStart - x) :
(x - leftMostEnd);
return
res;
}