Leecode 949. Largest Time for Given Digits

Chan Park
2 min readFeb 5, 2021

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: A = [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: A = [5,5,5,5]
Output: ""
Explanation: There are no valid 24-hour times as "55:55" is not valid.

Example 3:

Input: A = [0,0,0,0]
Output: "00:00"

Example 4:

Input: A = [0,0,1,0]
Output: "10:00"

Constraints:

  • arr.length == 4
  • 0 <= arr[i] <= 9
//Java
class LargestTime{
public static void main(String[] args) {
Solution sl = new Solution();
System.out.println(sl.largestTimeFromDigits(new int[]{1,2,3,4}));
System.out.println(sl.largestTimeFromDigits(new int[]{5,5,5,5}));
System.out.println(sl.largestTimeFromDigits(new int[]{0,0,0,0}));
System.out.println(sl.largestTimeFromDigits(new int[]{0,0,1,0}));
}
}

class Solution {
private int max_time = -1;

public String largestTimeFromDigits(int[] A) {
this.max_time = -1;
permutate(A, 0);
if (this.max_time == -1)
return "";
else
return String.format("%02d:%02d", max_time / 60, max_time % 60);
}

protected void permutate(int[] array, int start) {
if (start == array.length) {
this.build_time(array);
return;
}
for (int i = start; i < array.length; ++i) {
this.swap(array, i, start);
this.permutate(array, start + 1);
this.swap(array, i, start);
}
}

protected void build_time(int[] perm) {
int hour = perm[0] * 10 + perm[1];
int minute = perm[2] * 10 + perm[3];
if (hour < 24 && minute < 60)
this.max_time = Math.max(this.max_time, hour * 60 + minute);
}

protected void swap(int[] array, int i, int j) {
if (i != j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}

--

--