Largest Time for Given Digits in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of 4 digits, we have to find the largest 24-hour time that can be made. We know that the smallest 24-hour time is 00:00, and the largest time is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight. We have to return the answer as a string of length 5. If there is no valid time to be returned, then return an empty string.

So, if the input is like [1,2,3,4], then the output will be "23:41"

To solve this, we will follow these steps −

  • Define a function isValid(), this will take string a,
  • if a[0] > '2', then −
    • return false
  • if a[0] is same as '2' and a[1] > '3', then −
    • return false
  • if a[3] > '5', then −
    • return false
  • return true
  • Define a function dfs(), this will take an array A, res, cur,
  • if size of cur is same as 5, then −
    • if isValid(cur) and cur > res, then −
      • res := cur
    • return
  • for initialize i := 0, when i < 4, update (increase i by 1), do −
    • if A[i] is not equal to -1, then −
      • tmp := A[i]
      • cur := cur + A[i] + ASCII of '0'
      • if size of cur is same as 2, then −
        • cur := cur concatenate with ':'
      • A[i] := -1
      • dfs(A, res, cur)
      • A[i] := tmp
      • delete last element from cur
      • if size of cur is same as 2, then −
        • delete last element from cur
  • From the main method do the following −
  • res := empty string, tmp := empty string
  • dfs(A, res, tmp)
  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   void dfs(vector<int>& A, string& res, string& cur) {
      if (cur.size() == 5) {
         if (isValid(cur) && cur > res)
            res = cur;
            return;
         }
         for (int i = 0; i < 4; ++i) {
            if (A[i] != -1) {
               int tmp = A[i];
               cur += A[i] + '0';
            if (cur.size() == 2)
               cur += ':';
               A[i] = -1;
               dfs(A, res, cur);
               A[i] = tmp;
               cur.pop_back();
               if (cur.size() == 2)
                  cur.pop_back();
            }
         }
   }
   bool isValid(const string a) {
      if (a[0] > '2')
         return false;
         if (a[0] == '2' && a[1] > '3')
            return false;
         if (a[3] > '5')
            return false;
         return true;
   }
   string largestTimeFromDigits(vector<int>& A) {
      string res = "", tmp = "";
      dfs(A, res, tmp);
      return res;
   }
};
main(){
Solution ob;
vector<int> v = {1,2,3,4};
cout << (ob.largestTimeFromDigits(v));
}

Input

{1,2,3,4}

Output

23:41
raja
Published on 06-Jul-2020 12:44:45
Advertisements