|
| 1 | +/** |
| 2 | + * 949. Largest Time for Given Digits |
| 3 | + * https://leetcode.com/problems/largest-time-for-given-digits/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an array arr of 4 digits, find the latest 24-hour time that can be made using |
| 7 | + * each digit exactly once. |
| 8 | + * |
| 9 | + * 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between |
| 10 | + * 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. |
| 11 | + * |
| 12 | + * Return the latest 24-hour time in "HH:MM" format. If no valid time can be made, return |
| 13 | + * an empty string. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[]} arr |
| 18 | + * @return {string} |
| 19 | + */ |
| 20 | +var largestTimeFromDigits = function(arr) { |
| 21 | + let result = ''; |
| 22 | + helper(arr, new Array(4).fill(false), []); |
| 23 | + return result; |
| 24 | + |
| 25 | + function helper(digits, used, current) { |
| 26 | + if (current.length === 4) { |
| 27 | + const hours = parseInt(current.slice(0, 2).join('')); |
| 28 | + const minutes = parseInt(current.slice(2).join('')); |
| 29 | + if (hours <= 23 && minutes <= 59) { |
| 30 | + const time = `${current[0]}${current[1]}:${current[2]}${current[3]}`; |
| 31 | + if (time > result) result = time; |
| 32 | + } |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + for (let i = 0; i < digits.length; i++) { |
| 37 | + if (!used[i]) { |
| 38 | + used[i] = true; |
| 39 | + current.push(digits[i]); |
| 40 | + helper(digits, used, current); |
| 41 | + current.pop(); |
| 42 | + used[i] = false; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | +}; |
0 commit comments