text: 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 endpoof segment covered by it ; Return the required answer ; Driver code ; Function call
code: def Segment ( x , l , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT ans = 2 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( x [ i ] - l [ i ] > x [ i - 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT elif ( x [ i ] + l [ i ] < x [ i + 1 ] ) : NEW_LINE INDENT x [ i ] = x [ i ] + l [ i ] NEW_LINE ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT x = [ 1 , 3 , 4 , 5 , 8 ] NEW_LINE l = [ 10 , 1 , 2 , 2 , 5 ] NEW_LINE n = len ( x ) NEW_LINE print ( Segment ( x , l , n ) ) NEW_LINE