Minimum distance to travel to cover all intervals | C # 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
using System ; class GFG { public class Interval { public int start , end ; public Interval ( int start , int end ) { this . start = start ; this . end = end ; } } ; static int minDistanceToCoverIntervals ( Interval [ ] intervals , int N , int x ) { int rightMostStart = int . MinValue ; int leftMostEnd = int . MaxValue ; 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 ) Console . Write ( " Not ▁ Possible ▁ to ▁ " + " cover ▁ all ▁ intervals STRNEWLINE " ) ; else Console . Write ( res + " STRNEWLINE " ) ; } }