text: Maximum time such that absolute difference between hour and minute lies in given range | Java program for the above approach ; Function checks whether given time is correct ; To check minute value of time ; To check hour value of time ; Changes in value is not allowed at position where ' ? ' is not present ; Function checks whether the absolute difference between hour and minute value is within [ L , R ] ; Checks if the difference is outside the give range ; Displays time in proper 24 - hour format ; Function find the desired value of time whose difference lies in the range [ L , R ] ; Decrease hour value from 23 to 0 ; Check if the hour value is valid if not valid then no need to change minute value , since time will still remain in valid , to check hour value flag is set to 1. ; Decrease minute value from 59 to 0 ; Check if the minute value is valid , if not valid then skip the current iteration , to check ' minute ' value flag is set to 0. ; Driver code ; Input time ; Difference range
code: import java . util . * ; class GFG { static boolean isValid ( char a1 , char a2 , String str , int flag ) { char v1 , v2 ; if ( flag == 0 ) { v1 = str . charAt ( 4 ) ; v2 = str . charAt ( 3 ) ; } else { v1 = str . charAt ( 1 ) ; v2 = str . charAt ( 0 ) ; } if ( v1 != a1 && v1 != ' ? ' ) return false ; if ( v2 != a2 && v2 != ' ? ' ) return false ; return true ; } static boolean inRange ( int hh , int mm , int L , int R ) { int a = Math . abs ( hh - mm ) ; if ( a < L a > R ) return false ; return true ; } static void displayTime ( int hh , int mm ) { if ( hh > 10 ) System . out . print ( hh + " : " ) ; else if ( hh < 10 ) System . out . print ( "0" + hh + " : " ) ; if ( mm > 10 ) System . out . println ( mm ) ; else if ( mm < 10 ) System . out . println ( "0" + mm ) ; } static void maximumTimeWithDifferenceInRange ( String str , int L , int R ) { int i = 0 , j = 0 ; int h1 , h2 , m1 , m2 ; for ( i = 23 ; i >= 0 ; i -- ) { h1 = i % 10 ; h2 = i / 10 ; if ( ! isValid ( ( char ) h1 , ( char ) h2 , str , 1 ) ) { continue ; } for ( j = 59 ; j >= 0 ; j -- ) { m1 = j % 10 ; m2 = j / 10 ; if ( ! isValid ( ( char ) m1 , ( char ) m2 , str , 0 ) ) { continue ; } if ( inRange ( i , j , L , R ) ) { displayTime ( i , j ) ; return ; } } } if ( inRange ( i , j , L , R ) ) displayTime ( i , j ) ; else System . out . println ( " - 1" ) ; } public static void main ( String [ ] args ) { String timeValue = " ? ? : ? ? " ; int L = 20 , R = 39 ; maximumTimeWithDifferenceInRange ( timeValue , L , R ) ; } }