Maximum possible time that can be formed from four digits | 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
function getFrequencyMap ( arr ) { var hashMap = { } ; for ( var i = 0 ; i < arr . length ; i ++ ) { if ( hashMap . hasOwnProperty ( arr [ i ] ) ) { hashMap [ arr [ i ] ] = hashMap [ arr [ i ] ] + 1 ; } else { hashMap [ arr [ i ] ] = 1 ; } } return hashMap ; } function hasDigit ( hashMap , digit ) { if ( hashMap . hasOwnProperty ( digit ) && hashMap [ digit ] > 0 ) { hashMap [ digit ] = hashMap [ digit ] - 1 ; return true ; } return false ; } function getMaxTime ( arr ) { var hashMap = getFrequencyMap ( arr ) ; var i ; var flag ; var time = " " ; flag = false ; for ( i = 2 ; i >= 0 ; i -- ) { if ( hasDigit ( hashMap , i ) ) { flag = true ; time += i ; break ; } } if ( ! flag ) { return " " ; } flag = false ; if ( time [ 0 ] === " " ) { 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 " " ; } time += " " ; flag = false ; for ( i = 5 ; i >= 0 ; i -- ) { if ( hasDigit ( hashMap , i ) ) { flag = true ; time += i ; break ; } } if ( ! flag ) { return " " ; } flag = false ; for ( i = 9 ; i >= 0 ; i -- ) { if ( hasDigit ( hashMap , i ) ) { flag = true ; time += i ; break ; } } if ( ! flag ) { return " " ; } return time ; } var arr = [ 0 , 0 , 0 , 9 ] ; document . write ( getMaxTime ( arr ) ) ;