Skip to content

Latest commit

 

History

History

949

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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/
// Author: github.com/lzl124631x
// 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;
    }
};