Maximum number of intersections possible for any of the N given segments | Javascript program for the above approach ; Function to find the maximum number of intersections one segment has with all the other given segments ; Stores the resultant maximum count ; Stores the starting and the ending polets ; Sort arrays polets in the ascending order ; Traverse the array arr [ ] ; Find the count of segments on left of ith segment ; Find the count of segments on right of ith segment ; Find the total segments not letersecting with the current segment ; Store the count of segments that letersect with the ith segment ; Update the value of count ; Return the resultant count ; Driver Code
function lower_bound ( a , low , high , element ) { while ( low < high ) { let middle = low + Math . floor ( ( high - low ) / 2 ) ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } function maximumLetersections ( arr , N ) { let count = 0 ; let L = Array . from ( { length : N } , ( _ , i ) => 0 ) ; let R = Array . from ( { length : N } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < N ; i ++ ) { L [ i ] = arr [ i ] [ 0 ] ; R [ i ] = arr [ i ] [ 1 ] ; } L . sort ( ) ; R . sort ( ) ; for ( let i = 0 ; i < N ; i ++ ) { let l = arr [ i ] [ 0 ] ; let r = arr [ i ] [ 1 ] ; let x = lower_bound ( L , 0 , N , l ) ; let y = N - lower_bound ( R , 0 , N , r + 1 ) ; let cnt = x + y ; cnt = N - cnt - 1 ; count = Math . max ( count , cnt ) ; } return count ; } let arr = [ [ 1 , 6 ] , [ 5 , 5 ] , [ 2 , 3 ] ] ; let N = arr . length ; document . write ( maximumLetersections ( arr , N ) ) ;