Similar Problems
Similar Problems not available
Largest Time For Given Digits - Leetcode Solution
Companies:
LeetCode: Largest Time For Given Digits Leetcode Solution
Difficulty: Medium
Problem Statement: You are given an array of 4 digits - nums. You can use these digits and the operators +, -, *, / any number of times to form an expression.
Write a function largestTimeFromDigits(nums) that returns the latest 24-hour time that can be made using all the digits exactly once. If no valid time can be made, return an empty string.
Example 1: Input: nums = [1,2,3,4] Output: "23:41" Explanation: The valid 24-hour times that can be made using these digits are "13:42", "14:23", "21:43", "23:41". The latest time is "23:41".
Example 2: Input: nums = [5,5,5,5] Output: "" Explanation: There are no valid 24-hour times that can be made using these digits.
Approach: We can use the brute force approach to check all possible permutations of the given digits and find the latest valid time.
Step 1: Generate all permutations of the given digits using the itertools.permutations function in python.
Step 2: For each permutation, check if it is a valid time. A valid time is one where the first two digits represent the hours and the last two digits represent the minutes and the hours are less than 24 and the minutes are less than 60.
Step 3: Store the valid times in a list and find the maximum time.
Step 4: Convert the maximum time to the required format and return it.
Code:
Here is the python code to solve the problem:
import itertools
class Solution: def largestTimeFromDigits(self, nums: List[int]) -> str: # generate all permutations of the digits perms = itertools.permutations(nums) valid_times = [] for perm in perms: # check if permutation is a valid time h1,h2,m1,m2 = perm hours = h110 + h2 minutes = m110 + m2 if hours < 24 and minutes < 60: valid_times.append((hours,minutes))
# find the maximum time
if valid_times:
max_time = max(valid_times)
return '{:02d}:{:02d}'.format(max_time[0],max_time[1])
else:
return ''
Largest Time For Given Digits Solution Code
1