IN C++, please enter comments and use code that is easy to follow! Given four di
ID: 3828691 • Letter: I
Question
IN C++, please enter comments and use code that is easy to follow!
Given four digits, find the maximum valid time that can be displayed on a digital clock (in 24-hour format) using those digits. For example, given digits 1, 8, 3, 2 the maximum valid time is "23:18". Note that "28:31" is not a valid time. Write a function: string MaxTime(int A, int B, int C, int D); that, given four integers A, B, C, D, returns the maximum valid time in string format "HH:MM" or "NOT POSSIBLE" if it is not possible to display a valid time. Examples: given 1, 8, 3, 2, the function Max Time should return "23:18". Given 2, 4, 0, 0 the function should return "20:40". Given 3, 0, 7, 0 the function should return "07:30" Given 9, 1, 9, 7 the function should return "NOT POSSIBLE". Since there is no possible valid time. Assume that: A, B, C, D are integers with in the range [0..9] In your solution, focus on correctness as well as the performance of your solution. Try to achieve O(n) if possible rather than O(n^2) solution.Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
string MaxTime(int a,int b, int c, int d)
{
string str="";
int t[5];
int arr[10];
for(int i=0;i<9;i++)
arr[i]=-1;
arr[a]+=1; arr[b]+=1;arr[c]+=1;arr[d]+=1;
if(arr[2]!=-1)
{
t[0]=2;
arr[2]-=1;
}
else if(arr[1]!=-1)
{arr[1]-=1;
t[0]=1;
}
else if(arr[0]!=-1)
{ arr[0]-=1;
t[0]=0;
}
else return "NOT POSSIBLE";
int i=9;
if(t[0]==2)
{ if(arr[3]!=-1)
{ arr[3]-=1;
t[1]=3;
}
else if(arr[2]!=-1)
{
t[0]=2;
arr[2]-=1;
}
else if(arr[1]!=-1)
{arr[1]-=1;
t[0]=1;
}
else if(arr[0]!=-1)
{ arr[0]-=1;
t[0]=0;
}
else return "NOT POSSIBLE";
}else {
while(i!=-1)
{ if(arr[i]!=-1)
{ arr[i]-=1;
t[1]=i;
break;
}
}
}
if(i==0 && arr[i]==-1)
return "NOT POSSIBLE";
i=5;
while(i!=-1)
{
if(arr[i]!=-1)
{
t[2]=i;
arr[i]-=1;
break;
}
}
if(i==0 &&arr[i]>=-1)
return "NOT POSSIBLE";
i=9;
while(i!=-1)
{
if(arr[i]!=-1)
{
t[3]=i;
arr[i]-=1;
}
}
if(i==0 &&arr[i]>=-1)
return "NOT POSSIBLE";
// cout<<t[0]<<t[1]<<t[2]<<t[3];
// str=""+t[0]+""+t[1]+":"+t[2]+""+t[3];
str[0]=t[0];
str[1]=t[1];
str[2]=":";
str[3]=t[2];
str[4]=t[3];
return str;
}
int main()
{
int A,B,C,D;
cin>>A>>B>>C>>D;
cout<<MaxTime(A,B,C,D);
}