Leetcode 2224. Minimum Number of Operations to Convert Time
You are given two strings current
and correct
representing two 24-hour times. The string current
represents the current time and the string correct
represents the time we want to achieve. Each string is in the format “HH:MM”, where HH
represents the hours and MM
represents the minutes.
You can perform two types of operations:
Return the minimum number of operations needed to convert current
to correct
.
Example:
Input: current = "02:30", correct = "04:35"
Output: 3
Input: current = "11:00", correct = "11:01"
Output: 1
current
time is already equal to the correct
time?
0
because no operations are needed.current
and correct
are valid time strings in the “HH:MM” format.Parse the Time Strings: Extract the hours and minutes from both current
and correct
.
Convert to Minutes: Convert both times to total minutes from the start of the day to simplify the calculation of the difference.
Calculate the Difference: Compute the difference in minutes between current
and correct
.
Calculate Operations:
60
minutes each) as possible.15
minute blocks as possible.5
minute blocks as possible.public class MinimumOperationsToConvertTime {
public int convertTime(String current, String correct) {
String[] currentParts = current.split(":");
String[] correctParts = correct.split(":");
int currentHours = Integer.parseInt(currentParts[0]);
int currentMinutes = Integer.parseInt(currentParts[1]);
int correctHours = Integer.parseInt(correctParts[0]);
int correctMinutes = Integer.parseInt(correctParts[1]);
int currentTotalMinutes = currentHours * 60 + currentMinutes;
int correctTotalMinutes = correctHours * 60 + correctMinutes;
int difference = correctTotalMinutes - currentTotalMinutes;
int operations = 0;
if (difference >= 60) {
operations += difference / 60;
difference %= 60;
}
if (difference >= 15) {
operations += difference / 15;
difference %= 15;
}
if (difference >= 5) {
operations += difference / 5;
difference %= 5;
}
operations += difference; // Remaining minutes
return operations;
}
public static void main(String[] args) {
MinimumOperationsToConvertTime solution = new MinimumOperationsToConvertTime();
System.out.println(solution.convertTime("02:30", "04:35")); // Output: 3
System.out.println(solution.convertTime("11:00", "11:01")); // Output: 1
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?