Minimum change in given value so that it lies in all given Ranges | Function to find the minimum difference in the number D such that D is inside of every range ; Loop to find the common range out of the given array of ranges . ; Storing the start and end index ; Sorting the range ; Finding the maximum starting value of common segment ; Finding the minimum ending value of common segment ; If there is no common segment ; If the given number is between the computed common range . ; Finding the minimum distance ; Driver Code ; Given array of ranges
function findMinimumOperation ( n , d , arrays ) { var cnt = 0 ; var first = Number . MIN_VALUE , end = Number . MAX_VALUE ; while ( n > 0 ) { var arr = [ arrays [ cnt ] [ 0 ] , arrays [ cnt ] [ 1 ] ] ; arr . sort ( ( a , b ) => a - b ) ; first = Math . max ( first , arr [ 0 ] ) ; end = Math . min ( end , arr [ 1 ] ) ; cnt ++ ; n -- ; } if ( first > end ) document . write ( " " ) ; else { if ( d >= first && d <= end ) { document . write ( " " ) ; } else document . write ( Math . min ( Math . abs ( first - d ) , Math . abs ( d - end ) ) ) ; } } var n = 3 , d = 3 ; var arrays = [ [ 0 , 7 ] , [ 2 , 14 ] , [ 4 , 6 ] ] ; findMinimumOperation ( n , d , arrays ) ;