Minimum number of intervals to cover the target interval | Function to find the minimum number of intervals in the array A [ ] to cover the entire target interval ; Sort the array A [ ] in increasing order of starting point ; Insert a pair of INT_MAX to prevent going out of bounds ; Stores start of current interval ; Stores end of current leterval ; Stores the count of intervals ; Iterate over all the intervals ; If starting point of current index <= start ; Update the value of start ; Increment the value of count ; If the target interval is already covered or it is not possible to move then break the loop ; If the entire target interval is not covered ; Return Answer ; Driver Code
function minimizeSegment ( A , X ) { A . sort ( function ( a , b ) { return a . first - b . first ; } ) A . push ( { first : Number . MAX_VALUE , second : Number . MAX_VALUE } ) ; let start = X . first ; let end = X . first - 1 ; let cnt = 0 ; for ( let i = 0 ; i < A . length ; ) { if ( A [ i ] . first <= start ) { end = Math . max ( A [ i ++ ] . second , end ) ; } else { start = end ; ++ cnt ; if ( A [ i ] . first > end end >= X . second ) { break ; } } } if ( end < X . second ) { return - 1 ; } return cnt ; } let A = [ { first : 1 , second : 3 } , { first : 2 , second : 4 } , { first : 2 , second : 10 } , { first : 2 , second : 3 } , { first : 1 , second : 1 } ] ; let X = { first : 1 , second : 10 } ; document . write ( minimizeSegment ( A , X ) ) ;