Posted on

Description

Submission

class Solution {
public:
    string largestTimeFromDigits(vector<int>& A) {
        vector<int> max_time(4, 0);
        vector<bool> taken(4, false);
        bool isFoundOne = false;
        for(int a = 0; a < A.size(); ++a) {
            taken[a] = true;
            for(int b = 0; b < A.size(); ++b) {
                if(taken[b]) continue;
                taken[b] = true;
                for(int c = 0; c < A.size(); ++c) {
                    if(taken[c]) continue;
                    taken[c] = true;
                    for(int d = 0; d < A.size(); ++d) {
                        if(taken[d]) continue;
                        vector<int> new_time{A[a], A[b], A[c], A[d]};
                        if(!isValidTime(new_time)) break;
                        isFoundOne = true;
                        if(isBiggerThan(new_time, max_time)) {
                            max_time = new_time;
                        }
                    }
                    taken[c] = false;
                }
                taken[b] = false;
            }
            taken[a] = false;
        }
        
        if(!isFoundOne) return "";
        stringstream ss;
        ss << max_time[0] << max_time[1] << ":" << max_time[2] << max_time[3];
        return ss.str();
    }
private:
    bool isValidTime(vector<int>& time)
    {
        int hour = time[0] * 10 + time[1];
        int minutes = time[2] * 10 + time[3];
        return (hour >= 0 && hour <= 23 && minutes >= 0 && minutes <= 59);
    }
    bool isBiggerThan(vector<int>& time1, vector<int>& time2)
    {
        int h1 = time1[0] * 10 + time1[1];
        int m1 = time1[2] * 10 + time1[3];
        int h2 = time2[0] * 10 + time2[1];
        int m2 = time2[2] * 10 + time2[3];
        if(h1 > h2) return true;
        if(h1 == h2) return m1 > m2;
        return false;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *