Minimum change in given value so that it lies in all given Ranges | Java implementation find the minimum difference in the number D such that D is inside of every range ; 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
import java . util . * ; class GFG { static void findMinimumOperation ( int n , int d , int arrays [ ] [ ] ) { int cnt = 0 ; int first = Integer . MIN_VALUE , end = Integer . MAX_VALUE ; while ( n > 0 ) { int arr [ ] = { arrays [ cnt ] [ 0 ] , arrays [ cnt ] [ 1 ] } ; Arrays . sort ( arr ) ; first = Math . max ( first , arr [ 0 ] ) ; end = Math . min ( end , arr [ 1 ] ) ; cnt ++ ; n -- ; } if ( first > end ) System . out . print ( " - 1" ) ; else { if ( d >= first && d <= end ) { System . out . print ( "0" ) ; } else System . out . print ( Math . min ( Math . abs ( first - d ) , Math . abs ( d - end ) ) ) ; } } public static void main ( String [ ] args ) { int n = 3 , d = 3 ; int arrays [ ] [ ] = { { 0 , 7 } , { 2 , 14 } , { 4 , 6 } } ; findMinimumOperation ( n , d , arrays ) ; } }