I encountered this question in one of the interview challenges.
The question was that given four integers, display the maximum time possible in 24 hour format HH:MM. For example, if you are give A = 1, B = 9, C = 9, D = 2 then output should be 19:29. Max time can be 23:59 and min time can be 00:00. If it is not possible to construct 24 hour time then return error. For example, given A = 1, B = 9, C = 7, D = 9 an error should be returned since minimum time represented by these integers is 17:99 which is invalid.
My initial approach has been to find all the 24 integer permutations of given number and then eliminate all of them which are greater than 2400. After this, eliminate all the integers that have more than 59 in their last two digits. That is, 5 in the ten's place and 9 in the unit's place. After this filtering, return the highest integer left in our result set.
This approach is feasible here since we have to just calculate 24 permutations and even less combinations since duplicates will be removed. But I feel this to be a brute force approach. Is there any other idea which does not require us to generate all permutations?
Also as an extension to this problem, in case if we are asked to extend the time to seconds or milliseconds given total of 6 digits or 8 digits respectively, then my approach would be costly. Lets assume the max allowed run time complexity can be O(nlogn) and thus allowing us sorting. Also, how to check for the edge cases that I mentioned above?
Thanks.
EDIT: Below is the code for the answer suggested in the comments.
//Input arraylist contains the four integers
public static String maxTime(ArrayList<Integer> list){
int first = -1;
int second = -1;
int third = -1;
int fourth = -1;
for (int a : list) {
if (a <= 2 && a > first) {
first = a;
}
}
list.remove(Integer.valueOf(first));
for (int a : list) {
if (first == 2 && a <= 3 && a > second) {
second = a;
}
}
if (second == -1) {
for (int a : list) {
if (a > second) {
second = a;
}
}
}
list.remove(Integer.valueOf(second));
for (int a : list) {
if (a <= 5 && a > third) {
third = a;
}
}
list.remove(Integer.valueOf(third));
fourth = list.get(0);
StringBuilder sb = new StringBuilder(5);
sb.append(first);
sb.append(second);
sb.append(':');
sb.append(third);
sb.append(fourth);
return sb.toString();
}