Maximum number of overlapping Intervals | Java program that print maximum number of overlap among given ranges ; Function that print maximum overlap among ranges ; Variable to store the maximum count ; Storing the x and y coordinates in data vector ; Pushing the x coordinate ; pushing the y coordinate ; Sorting of ranges ; Traverse the data vector to count number of overlaps ; If x occur it means a new range is added so we increase count ; If y occur it means a range is ended so we decrease count ; Updating the value of ans after every traversal ; Printing the maximum value ; Driver code
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static class pair { int first ; char second ; pair ( int first , char second ) { this . first = first ; this . second = second ; } } static void overlap ( int [ ] [ ] v ) { int ans = 0 ; int count = 0 ; ArrayList < pair > data = new ArrayList < > ( ) ; for ( int i = 0 ; i < v . length ; i ++ ) { data . add ( new pair ( v [ i ] [ 0 ] , ' x ' ) ) ; data . add ( new pair ( v [ i ] [ 1 ] , ' y ' ) ) ; } Collections . sort ( data , ( a , b ) -> a . first - b . first ) ; for ( int i = 0 ; i < data . size ( ) ; i ++ ) { if ( data . get ( i ) . second == ' x ' ) count ++ ; if ( data . get ( i ) . second == ' y ' ) count -- ; ans = Math . max ( ans , count ) ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int [ ] [ ] v = { { 1 , 2 } , { 2 , 4 } , { 3 , 6 } } ; overlap ( v ) ; } }