Minimum change in given value so that it lies in all given Ranges | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumOperation ( int n , int d , int arrays [ 3 ] [ 2 ] ) { int cnt = 0 ; int first = INT_MIN , end = INT_MAX ; while ( n -- ) { int arr [ 2 ] = { arrays [ cnt ] [ 0 ] , arrays [ cnt ] [ 1 ] } ; sort ( arr , arr + 2 ) ; first = max ( first , arr [ 0 ] ) ; end = min ( end , arr [ 1 ] ) ; cnt ++ ; } if ( first > end ) cout << " - 1" ; else { if ( d >= first && d <= end ) { cout << "0" ; } else cout << min ( abs ( first - d ) , abs ( d - end ) ) ; } } int main ( ) { int n = 3 , d = 3 ; int arrays [ 3 ] [ 2 ] = { { 0 , 7 } , { 2 , 14 } , { 4 , 6 } } ; findMinimumOperation ( n , d , arrays ) ; }