Skip to content

949. Largest Time for Given Digits 👎

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  string largestTimeFromDigits(vector<int>& arr) {
    string ans;

    for (int i = 0; i < 4; ++i)
      for (int j = 0; j < 4; ++j)
        for (int k = 0; k < 4; ++k) {
          if (i == j || i == k || j == k)
            continue;
          const string hours = to_string(arr[i]) + to_string(arr[j]);
          const string minutes =
              to_string(arr[k]) + to_string(arr[6 - i - j - k]);
          if (hours < "24" && minutes < "60")
            ans = max(ans, hours + ':' + minutes);
        }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public String largestTimeFromDigits(int[] arr) {
    String ans = "";

    for (int i = 0; i < 4; ++i)
      for (int j = 0; j < 4; ++j)
        for (int k = 0; k < 4; ++k) {
          if (i == j || i == k || j == k)
            continue;
          final String hours = "" + arr[i] + arr[j];
          final String minutes = "" + arr[k] + arr[6 - i - j - k];
          final String time = hours + ':' + minutes;
          if (hours.compareTo("24") < 0 && minutes.compareTo("60") < 0 && ans.compareTo(time) < 0)
            ans = time;
        }

    return ans;
  }
}
1
2
3
4
5
6
class Solution:
  def largestTimeFromDigits(self, arr: list[int]) -> str:
    for time in itertools.permutations(sorted(arr, reverse=True)):
      if time[:2] < (2, 4) and time[2] < 6:
        return '%d%d:%d%d' % time
    return ''