VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-time-such-that-absolute-difference-between-hour-and-minute-lies-in-given-range/

⇱ Maximum time such that absolute difference between hour and minute lies in given range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum time such that absolute difference between hour and minute lies in given range

Last Updated : 10 Jun, 2021

Given a 24-hour time value, where on some numbers are question marks( '?' ), and two integers L and R. The question mark can be replaced with any number. The task is to find the maximum time such that the absolute difference between hour value and minute value lies in the interval [L, R]. If no possible value of time exists, then print -1.

Examples:

Input : time = "2?:03", L = 5, R = 18 
Output : 21:03 
Explanation : Since, the difference is 21 - 3 = 18 and the time value 21:03 is the largest possible value whose difference lies in the range [5, 18]

Input : time = "??:??", L = 60, R = 69 
Output : -1 
Explanation : Since maximum possible difference between hour value and minute value is 59. So, no time value is possible. 
 

Approach : 
We will run two nested loops, one to represent 'hour' value from 23 to 0 and another to represent 'minute' value from 59 to 0. We keep decreasing 'hour' and 'minute' value until we get the desired time value.  

  1. Since the maximum time value is desired, so we decrease the 'hour' value from 23 to 0 and similarly 'minute' value from 59 to 0.
  2. After decreasing the 'hour' and 'minute' value, we need to check if the 'hour' and 'minute' value is valid or not.
  3. Change in value of 'hour' and 'minute' is allowed only at those positions which have '?'. Changes at other positions will make time value invalid. To ensure this we will call function isValid().
  4. Keep on decreasing 'hour' and 'minute' value until a valid time is found whose difference lies in the range [ L, R ].
  5. If no valid time is found, then print “-1”.

Below is the implementation of the above approach: 


Output: 
23:59

 

Time Complexity: O(1) 
Auxiliary Space: O(1)

Comment
Article Tags: