Maximum number of elements without overlapping in a Line | Function to find maximum number of elements without overlapping in a line ; If n = 1 , then answer is one ; We can always make 1 st element to cover left segment and nth the right segment ; If left segment for ith element doesnt overlap with i - 1 th element then do left ; else try towards right if possible ; update x [ i ] to right endpolet of segment covered by it ; Return the required answer ; Driver code ; Function call
function Segment ( x , l , n ) { if ( n == 1 ) return 1 ; let ans = 2 ; for ( let i = 1 ; i < n - 1 ; i ++ ) { if ( x [ i ] - l [ i ] > x [ i - 1 ] ) ans ++ ; else if ( x [ i ] + l [ i ] < x [ i + 1 ] ) { x [ i ] = x [ i ] + l [ i ] ; ans ++ ; } } return ans ; } let x = [ 1 , 3 , 4 , 5 , 8 ] , l = [ 10 , 1 , 2 , 2 , 5 ] ; let n = x . length ; document . write ( Segment ( x , l , n ) ) ;