# Maximum possible time that can be formed from four digits in C++

In this tutorial, we will be discussing a program to find maximum possible time that can be formed from four digits.

For this we will be provided with an array consisting 4 digits. Our task is to find the maximum time (24 hour format) that can formed using those four digits.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//returning updated frequency map
map<int, int> getFrequencyMap(int arr[], int n) {
map<int, int> hashMap;
for (int i = 0; i < n; i++) {
hashMap[arr[i]]++;
}
return hashMap;
}
//checking if the digit is present in frequency map
bool hasDigit(map<int, int>* hashMap, int digit) {
if ((*hashMap)[digit]) {
(*hashMap)[digit]--;
return true;
}
return false;
}
//returning maximum time in 24 hour format
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;
}

## Output

09:00

Updated on: 09-Sep-2020

236 Views