Description
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.
Example 1:
Input: arr = [1,2,3,4] Output: "23:41" Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.
Example 2:
Input: arr = [5,5,5,5] Output: "" Explanation: There are no valid 24-hour times as "55:55" is not valid.
Constraints:
arr.length == 40 <= arr[i] <= 9
Solutions
Solution 1
PythonJavaC++Go
class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: cnt = [0] * 10 for v in arr: cnt[v] += 1 for h in range(23, -1, -1): for m in range(59, -1, -1): t = [0] * 10 t[h // 10] += 1 t[h % 10] += 1 t[m // 10] += 1 t[m % 10] += 1 if cnt == t: return f'{h:02}:{m:02}' return ''(code-box)
Solution 2
Python
class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: ans = -1 for i in range(4): for j in range(4): for k in range(4): if i != j and i != k and j != k: h = arr[i] * 10 + arr[j] m = arr[k] * 10 + arr[6 - i - j - k] if h < 24 and m < 60: ans = max(ans, h * 60 + m) return '' if ans < 0 else f'{ans // 60:02}:{ans % 60:02}'(code-box)
