949. Largest Time for Given Digits - Easy

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

 

permutation + backtracking

time = O(1) -- length of the array is fixed, space = O(1)

class Solution {
    
    private int maxTime = -1;
    
    public String largestTimeFromDigits(int[] A) {
        maxTime = -1;
        permute(A, 0);
        if(maxTime == -1) {
            return "";
        } else {
            return String.format("%02d:%02d", maxTime / 60, maxTime % 60);
        }
    }
    
    private void permute(int[] arr, int start) {
        if(start == arr.length) {
            buildTime(arr);
            return;
        }
        for(int i = 0; i < arr.length; i++) {
            swap(arr, i, start);
            permute(arr, start + 1);
            swap(arr, i, start);
        }
    }
    
    private void buildTime(int[] arr) {
        int hour = arr[0] * 10 + arr[1];
        int minute = arr[2] * 10 + arr[3];
        if(hour < 24 && minute < 60) {
            maxTime = Math.max(maxTime, hour * 60 + minute);
        }
    }
    
    private void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}

 

posted @ 2020-09-02 13:42  fatttcat  阅读(221)  评论(0编辑  收藏  举报