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

前端 未结 23 2067
执念已碎
执念已碎 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:59

    from itertools  import permutations
    class Solution(object):
        def largestTimeFromDigits(self, A):
            arr = []
            for i in permutations(A,4):
                if int(str(i[0])+str(i[1])) < 24 and int(str(i[2])+ str(i[3])) < 60:
                    arr.append(list(i))
            
            if arr:
                cnt = arr[0]
                for t in arr[1:]:
                    if int(str(t[0])+str(t[1])) > int(str(cnt[0])+ str(cnt[1])):
                        cnt = t
                    elif int(str(t[0])+str(t[1])) == int(str(cnt[0])+ str(cnt[1])):
                        if int(str(t[2])+str(t[3])) > int(str(cnt[2])+ str(cnt[3])):
                            cnt = t
                return str(cnt[0])+ str(cnt[1]) + ":" + str(cnt[2])+ str(cnt[3])  
            else:
                return ""
    

提交回复
热议问题