[LeetCode] Largest Time for Given Digits

949. Largest Time for Given Digits

Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.

24-hour times are formatted as “HH:MM”, where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.

Return the latest 24-hour time in “HH:MM” format. If no valid time can be made, return an empty string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
string largestTimeFromDigits(vector<int>& arr) {
sort(arr.begin(), arr.end());
for(int a = 3; a >= 0; a--) {
if(arr[a] >= 3) continue;
for(int b = 3; b >= 0; b--) {
if(a == b || (arr[a] == 2 && arr[b] >= 4)) continue;
for(int c = 3; c >= 0; c--) {
if(a == c || b == c || arr[c] >= 6) continue;
for(int d = 3; d >= 0; d--) {
if(a == d || b == d || c == d) continue;
return to_string(arr[a]) + to_string(arr[b]) + ":" + to_string(arr[c]) + to_string(arr[d]);
}
}
}
}

return "";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/19/PS/LeetCode/largest-time-for-given-digits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.