Maximum possible time that can be formed from four digits | Java implementation of the approach ; Function to return the updated frequency map for the array passed as argument ; Function that returns true if the passed digit is present in the map after decrementing it 's frequency by 1 ; If map contains the digit ; Decrement the frequency of the digit by 1 ; True here indicates that the digit was found in the map ; Digit not found ; Function to return the maximum possible time in 24 - Hours format ; First digit of hours can be from the range [ 0 , 2 ] ; If no valid digit found ; If first digit of hours was chosen as 2 then the second digit of hours can be from the range [ 0 , 3 ] ; Else it can be from the range [ 0 , 9 ] ; Hours and minutes separator ; First digit of minutes can be from the range [ 0 , 5 ] ; Second digit of minutes can be from the range [ 0 , 9 ] ; Return the maximum possible time ; Driver code
import java . util . * ; public class GFG { static HashMap < Integer , Integer > getFrequencyMap ( int arr [ ] ) { HashMap < Integer , Integer > hashMap = new HashMap < > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( hashMap . containsKey ( arr [ i ] ) ) { hashMap . put ( arr [ i ] , hashMap . get ( arr [ i ] ) + 1 ) ; } else { hashMap . put ( arr [ i ] , 1 ) ; } } return hashMap ; } static boolean hasDigit ( HashMap < Integer , Integer > hashMap , int digit ) { if ( hashMap . containsKey ( digit ) && hashMap . get ( digit ) > 0 ) { hashMap . put ( digit , hashMap . get ( digit ) - 1 ) ; return true ; } return false ; } static String getMaxTime ( int arr [ ] ) { HashMap < Integer , Integer > hashMap = getFrequencyMap ( arr ) ; int i ; boolean flag ; String time = " " ; flag = false ; for ( i = 2 ; i >= 0 ; i -- ) { if ( hasDigit ( hashMap , i ) ) { flag = true ; time += i ; break ; } } if ( ! flag ) { return " - 1" ; } flag = false ; if ( time . charAt ( 0 ) == '2' ) { for ( i = 3 ; i >= 0 ; i -- ) { if ( hasDigit ( hashMap , i ) ) { flag = true ; time += i ; break ; } } } else { for ( i = 9 ; i >= 0 ; i -- ) { if ( hasDigit ( hashMap , i ) ) { flag = true ; time += i ; break ; } } } if ( ! flag ) { return " - 1" ; } time += " : " ; flag = false ; for ( i = 5 ; i >= 0 ; i -- ) { if ( hasDigit ( hashMap , i ) ) { flag = true ; time += i ; break ; } } if ( ! flag ) { return " - 1" ; } flag = false ; for ( i = 9 ; i >= 0 ; i -- ) { if ( hasDigit ( hashMap , i ) ) { flag = true ; time += i ; break ; } } if ( ! flag ) { return " - 1" ; } return time ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 0 , 0 , 9 } ; System . out . println ( getMaxTime ( arr ) ) ; } }