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
class Solution {
 public:
  string largestTimeFromDigits(vector<int>& A) {
    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;
          string hours = to_string(A[i]) + to_string(A[j]);
          string minutes = to_string(A[k]) + to_string(A[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[] A) {
    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;
          String hours = "" + A[i] + A[j];
          String minutes = "" + A[k] + A[6 - i - j - k];
          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
7
class Solution:
  def largestTimeFromDigits(self, A: List[int]) -> str:
    for time in itertools.permutations(sorted(A, reverse=True)):
      if time[:2] < (2, 4) and time[2] < 6:
        return '%d%d:%d%d' % time

    return ''