Find maximum possible time HH:MM by permuting four given digits

前端 未结 23 2175
执念已碎
执念已碎 2020-11-30 02:44

I recently took a coding test for a promotion at work. This was one of the tasks I really struggled with and was wondering what is the best way to do this. I used a load of

23条回答
  •  孤街浪徒
    2020-11-30 02:49

    I recently was working on the same problem (with 6 digits though) and came up with this non-brute solution:

      #include 
      #include 
    
      int numbers[6] = { 0, 0, 0, 0, 0, 0 };
      int input[6] = { 1, 7, 3, 3, 4, 1 };
    
      void buildHistogram() {
          for (int i = 0; i < 6; ++i) {
              numbers[input[i]]++;
          }
      }
    
      int getMaxNotExceeding(int number) {
          for (int i = number; i >= 0; --i) {
              if (numbers[i] > 0) {
                  numbers[i]--;
                  return i;
              }
          }
          throw std::exception("CANNOT CREATE TIME");
      }
    
      int main() {
          try {
              buildHistogram();
              int hours = (getMaxNotExceeding(2) * 10);
              if (hours < 20) {
                hours += getMaxNotExceeding(9);
              } else {
                hours += getMaxNotExceeding(3);
              }
              int minutes = (getMaxNotExceeding(5) * 10) + getMaxNotExceeding(9);
              int seconds = (getMaxNotExceeding(5) * 10) + getMaxNotExceeding(9);
    
              if (seconds > 59 || minutes > 59 || hours > 23) {
                  throw std::exception("CANNOT CREATE TIME");
              }
              std::cout.fill('0');
              std::cout << std::setw(2) << hours << ':' << std::setw(2) << minutes << ':' << std::setw(2) << seconds << std::endl;
          } catch(const std::exception& ex) {
              std::cout << ex.what() << std::endl;
          }
          return 0;
      }
    

提交回复
热议问题