Leetcode: Largest Time for Given Digits

Largest Time for Given Digits



Similar Problems:


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:

  • A.length == 4
  • 0 <= A[i] <= 9

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// Blog link: https://code.dennyzhang.com/largest-time-for-given-digits
// Basic Idea: Only 24 different cases
// Complexity: Time O(1), Space O(1)
import ("math"
        "sort")

func combination(A []int) []int {
    if len(A) == 0 { return []int{} }
    if len(A) == 1 { return []int{A[0]} }
    l := []int{}
    for i, _ := range A {
        v1 := A[i]*int(math.Pow(10, float64(len(A)-1)))
        l2 := make([]int, len(A)-1)
        for j:=0; j<i; j++ {
            l2[j] = A[j]
        }
        for j:=i+1; j<len(A); j++ {
            l2[j-1] = A[j]
        }
        for _, v2 := range combination(l2) {
            l = append(l, v1+v2)
        }
    }
    return l
}

func largestTimeFromDigits(A []int) string {
    l := combination(A)
    sort.Ints(l)
    for i:=len(l)-1; i>=0; i-- {
        if l[i] >= 2400 { continue }
        if l[i]%100 < 60 {
            return fmt.Sprintf("%02d:%02d", int(l[i]/100), l[i]%100)
        }
    }
    return ""
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.