Maximum ranges that can be uniquely represented by any integer from the range | java program for the above approach ; Function to find the maximum number of ranges where each range can be uniquely represented by an integer ; Sort the ranges in ascending order ; Stores the count of ranges ; Stores previously assigned range ; Traverse the vector arr [ ] ; Skip the similar ranges of size 1 ; Find the range of integer available to be assigned ; Check if an integer is available to be assigned ; Update the previously assigned range ; Update the count of range ; Return the maximum count of ranges ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static int maxRanges ( Integer arr [ ] [ ] , int N ) { Arrays . sort ( arr , ( a , b ) -> { if ( a [ 0 ] . equals ( b [ 0 ] ) ) return Integer . compare ( a [ 1 ] , b [ 1 ] ) ; return Integer . compare ( a [ 0 ] , b [ 0 ] ) ; } ) ; int count = 1 ; Integer prev [ ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { Integer last [ ] = arr [ i - 1 ] ; Integer current [ ] = arr [ i ] ; if ( last [ 0 ] == current [ 0 ] && last [ 1 ] == current [ 1 ] && current [ 1 ] == current [ 0 ] ) continue ; int start = Math . max ( prev [ 0 ] , current [ 0 ] - 1 ) ; int end = Math . max ( prev [ 1 ] , current [ 1 ] ) ; if ( end - start > 0 ) { prev [ 0 ] = 1 + start ; prev [ 1 ] = end ; count ++ ; } } return count ; } public static void main ( String [ ] args ) { Integer range [ ] [ ] = { { 1 , 4 } , { 4 , 4 } , { 2 , 2 } , { 3 , 4 } , { 1 , 1 } } ; int N = range . length ; System . out . print ( maxRanges ( range , N ) ) ; } }