Minimum distance to travel to cover all intervals | Java program to find minimum distance to travel to cover all intervals ; Structure to store an interval ; Method returns minimum distance to travel to cover all intervals ; Looping over all intervals to get right most start and left most end ; If rightmost start > leftmost end then all intervals are not aligned and it is not possible to cover all of them ; If x is in between rightmoststart and leftmostend then no need to travel any distance ; Choose minimum according to current position x ; Driver code
import java . util . * ; class GFG { static class Interval { int start , end ; Interval ( int start , int end ) { this . start = start ; this . end = end ; } } ; static int minDistanceToCoverIntervals ( Interval intervals [ ] , int N , int x ) { int rightMostStart = Integer . MIN_VALUE ; int leftMostEnd = Integer . MAX_VALUE ; 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 ( rightMostStart > leftMostEnd ) res = - 1 ; else if ( rightMostStart <= x && x <= leftMostEnd ) res = 0 ; else res = ( x < rightMostStart ) ? ( rightMostStart - x ) : ( x - leftMostEnd ) ; return res ; } public static void main ( String [ ] args ) { int x = 3 ; Interval [ ] intervals = { new Interval ( 0 , 7 ) , new Interval ( 2 , 14 ) , new Interval ( 4 , 6 ) } ; int N = intervals . length ; int res = minDistanceToCoverIntervals ( intervals , N , x ) ; if ( res == - 1 ) System . out . print ( " Not ▁ Possible ▁ to ▁ " + "cover all intervalsNEW_LINE"); else System . out . print ( res + "NEW_LINE"); } }