Maximum possible time that can be formed from four digits | C ++ 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_value 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_value ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; map < int , int > getFrequencyMap ( int arr [ ] , int n ) { map < int , int > hashMap ; for ( int i = 0 ; i < n ; i ++ ) { hashMap [ arr [ i ] ] ++ ; } return hashMap ; } bool hasDigit ( map < int , int > * hashMap , int digit ) { if ( ( * hashMap ) [ digit ] ) { ( * hashMap ) [ digit ] -- ; return true ; } return false ; } string getMaxtime_value ( int arr [ ] , int n ) { map < int , int > hashMap = getFrequencyMap ( arr , n ) ; int i ; bool flag ; string time_value = " " ; flag = false ; for ( i = 2 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } if ( ! flag ) return " - 1" ; flag = false ; if ( time_value [ 0 ] == '2' ) { for ( i = 3 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } } else { for ( i = 9 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } } if ( ! flag ) return " - 1" ; time_value += " : " ; flag = false ; for ( i = 5 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } if ( ! flag ) return " - 1" ; flag = false ; for ( i = 9 ; i >= 0 ; i -- ) { if ( hasDigit ( & hashMap , i ) ) { flag = true ; time_value += ( char ) i + 48 ; break ; } } if ( ! flag ) return " - 1" ; return time_value ; } int main ( ) { int arr [ ] = { 0 , 0 , 0 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << ( getMaxtime_value ( arr , n ) ) ; return 0 ; }