LeetCode 2224: Minimum Number of Operations to Convert Time

StringGreedy

Problem Description

Explanation

To solve this problem, we can iterate through each digit of the current and correct times and calculate the difference between them. Based on this difference, we can determine the minimum number of operations needed to convert the current time to the correct time. The possible operations are adding 1, 5, 15, or 60 minutes.

  1. Parse the current and correct times into hours and minutes.
  2. Calculate the total minutes for both times.
  3. Calculate the difference in minutes between the current and correct times.
  4. Determine the minimum number of operations needed based on the difference.
  5. Return the minimum number of operations.

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

Solutions

class Solution {
    public int minOperations(String current, String correct) {
        int currentHours = Integer.parseInt(current.substring(0, 2));
        int currentMinutes = Integer.parseInt(current.substring(3));
        int correctHours = Integer.parseInt(correct.substring(0, 2));
        int correctMinutes = Integer.parseInt(correct.substring(3));

        int currentTotalMinutes = currentHours * 60 + currentMinutes;
        int correctTotalMinutes = correctHours * 60 + correctMinutes;

        int diff = Math.abs(currentTotalMinutes - correctTotalMinutes);

        int operations = 0;
        while (diff > 0) {
            if (diff >= 60) {
                operations += diff / 60;
                diff %= 60;
            } else if (diff >= 15) {
                operations += diff / 15;
                diff %= 15;
            } else if (diff >= 5) {
                operations += diff / 5;
                diff %= 5;
            } else {
                operations += diff;
                diff = 0;
            }
        }

        return operations;
    }
}

Loading editor...