Maximum number of segments that can contain the given points | Function to return the maximum number of segments ; Sort both the vectors ; Initially pointing to the first element of b [ ] ; Try to find a match in b [ ] ; The segment ends before b [ j ] ; The point lies within the segment ; The segment starts after b [ j ] ; Return the required count ; Driver code
function countPoints ( n , m , a , b , x , y ) { a . sort ( function ( a , b ) { return a - b } ) ; b . sort ( function ( a , b ) { return a - b } ) ; let j = 0 ; let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) { while ( j < m ) { if ( a [ i ] + y < b [ j ] ) break ; if ( b [ j ] >= a [ i ] - x && b [ j ] <= a [ i ] + y ) { count ++ ; j ++ ; break ; } else j ++ ; } } return count ; } let x = 1 , y = 4 ; let a = [ 1 , 5 ] ; let n = a . length ; let b = [ 1 , 1 , 2 ] ; let m = a . length ; document . write ( countPoints ( n , m , a , b , x , y ) ) ;