Formatted question description: https://leetcode.ca/all/949.html

949. Largest Time for Given Digits (Easy)

Given an array of 4 digits, return the largest 24 hour time that can be made.

The smallest 24 hour time is 00:00, and the largest is 23:59.  Starting from 00:00, a time is larger if more time has elapsed since midnight.

Return the answer as a string of length 5.  If no valid time can be made, return an empty string.

 

Example 1:

Input: [1,2,3,4]
Output: "23:41"

Example 2:

Input: [5,5,5,5]
Output: ""

 

Note:

  1. A.length == 4
  2. 0 <= A[i] <= 9

Related Topics:
Math

Solution 1.

// OJ: https://leetcode.com/problems/largest-time-for-given-digits/

// Time: O(1)
// Space: O(1)
class Solution {
private:
    string ans;
    void permute(string &s, int start) {
        if (start == s.size()) {
            ans = max(ans, s);
            return;
        }
        for (int i = start; i < s.size(); ++i) {
            if ((start == 0 && s[i] > '2')
               || (start == 1 && s[start - 1] == '2' && s[i] > '3')
               || (start == 2 && s[i] > '5')) continue;
            swap(s[start], s[i]);
            permute(s, start + 1);
            swap(s[start], s[i]);
        }
    }
public:
    string largestTimeFromDigits(vector<int>& A) {
        string s;
        for (int i : A) s.push_back('0' + i);
        permute(s, 0);
        if (ans.size()) ans.insert(2, ":");
        return ans;
    }
};

Java

class Solution {
    public String largestTimeFromDigits(int[] A) {
        int curHour = -1, curMinute = -1;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if (j == i)
                    continue;
                for (int k = 0; k < 4; k++) {
                    if (k == i || k == j)
                        continue;
                    int l = 6 - i - j - k;
                    int hour = A[i] * 10 + A[j], minute = A[k] * 10 + A[l];
                    if (hour <= 23 && minute <= 59) {
                        if (hour > curHour || hour == curHour && minute > curMinute) {
                            curHour = hour;
                            curMinute = minute;
                        }
                    }
                }
            }
        }
        return curHour >= 0 ? String.format("%02d:%02d", curHour, curMinute) : "";
    }
}

All Problems

All Solutions