Largest Time for Given Digits
Given an array of 4 digits, return the largest 24 hour time that can be made.
The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.
Return the answer as a string of length 5. If no valid time can be made, return an empty string.
Example 1:
Input: [1,2,3,4] Output: "23:41"
Example 2:
Input: [5,5,5,5] Output: ""
Note:
A.length == 4
0 <= A[i] <= 9
---------------------------------------------------------------------------------------------------------------------------
class Solution:
def largestTimeFromDigits(self, A: List[int]) -> str:
max_time = -1
# enumerate all possibilities, with the permutation() func
for h, i, j, k in itertools.permutations(A):
hour = h*10 + i
minute = j*10 + k
if hour < 24 and minute < 60:
max_time = max(max_time, hour * 60 + minute)
if max_time == -1:
return ""
else:
return "{:02d}:{:02d}".format(max_time // 60, max_time % 60)
---------------------------------------------------------------------------------------------------------------------------
class Solution {
public:
string largestTimeFromDigits(vector<int>& A) {
sort(begin(A), end(A), greater<int>());
do if ((A[0] < 2 || (A[0] == 2 && A[1] < 4)) && A[2] < 6)
return to_string(A[0]) + to_string(A[1]) + ":" + to_string(A[2]) + to_string(A[3]);
while (prev_permutation(begin(A), end(A)));
return "";
}
};
---------------------------------------------------------------------------------------------------------------------------
class Solution {
public:
string largestTimeFromDigits(vector<int>& A) {
int max_time = -1;
// prepare for the generation of permutations next.
std::sort(A.begin(), A.end());
do {
int hour = A[0] * 10 + A[1];
int minute = A[2] * 10 + A[3];
if (hour < 24 && minute < 60) {
int new_time = hour * 60 + minute;
max_time = new_time > max_time ? new_time : max_time;
}
} while(next_permutation(A.begin(), A.end()));
if (max_time == -1) {
return "";
} else {
std::ostringstream strstream;
strstream << std::setw(2) << std::setfill('0') << max_time / 60
-----------------------------------------------------------------------------------------------------------------------