title: Display maximum military time from given four integers
body: <p>I encountered this question in one of the interview challenges. </p>
  
  <p>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. </p>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p>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?</p>
  
  <p>Thanks.</p>
  
  <p>EDIT: Below is the code for the answer suggested in the comments.</p>
  
  <pre><code>//Input arraylist contains the four integers
  public static String maxTime(ArrayList&lt;Integer&gt; list){
      int first = -1;
      int second = -1;
      int third = -1;
      int fourth = -1;
  
      for (int a : list) {
          if (a &lt;= 2 &amp;&amp; a &gt; first) {
              first = a;
          }
      }
      list.remove(Integer.valueOf(first));
  
      for (int a : list) {
          if (first == 2 &amp;&amp; a &lt;= 3 &amp;&amp; a &gt; second) {
              second = a;
          }
      }
      if (second == -1) {
          for (int a : list) {
              if (a &gt; second) {
                  second = a;
              }
          }
      }
      list.remove(Integer.valueOf(second));
  
      for (int a : list) {
          if (a &lt;= 5 &amp;&amp; a &gt; 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();
  }
  </code></pre>