Link

Easy Math

Google

2020-09-01

949. Largest Time for Given Digits

Question:

Given an array of 4 digits, return the largest 24 hour time that can be made.

The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.

Return the answer as a string of length 5. If no valid time can be made, return an empty string.

Example 1:

Input: [1,2,3,4]
Output: "23:41"

Example 2:

Input: [5,5,5,5]
Output: ""

Note:

  1. A.length == 4
  2. 0 <= A[i] <= 9

Solution:

Enumerate each combination and find the max result with boundary check.

class Solution {
    public String largestTimeFromDigits(int[] A) {
        int result = -1;
        for(int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                for (int k = 0; k < 4; k++) {
                    if (i == j || i == k || j == k) {
                        continue;
                    }
                    int h = A[i] * 10 + A[j];
                    int m = A[k] * 10 + A[6-i-j-k];
                    if (isValidTime(h, m)) {
                        result = Math.max(result, h * 60 + m);
                    } 
                }
            }
        } 
        if (result == -1){
            return "";
        }
        return String.format("%02d:%02d", result / 60, result % 60);
        
    }
    
    private boolean isValidTime(int h, int m) {
        if (h >= 0 && h <= 23 && m >= 0 && m <= 59) {
            return true;
        }
        return false;
    }
}