Opening the reading…
Opening the reading…
GREEDY › PART I
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →The clock format hides the quantity that matters. Once each time is written as minutes since midnight, the problem becomes choosing the fewest values from 60, 15, 5, and 1 whose sum equals the difference between the two times. The guarantee that current is no later than correct means this difference is never negative.
An operation with a larger increment can replace several smaller operations whenever it fits. Therefore, take as many 60-minute operations as possible, then as many 15-minute operations as possible, followed by 5 and finally 1. After each choice, the remainder is smaller than the increment just used, so no later choice could have replaced one of those operations with fewer operations.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(1) | Each time is parsed from two fixed-width fields, and the loop examines exactly four increments. No operation depends on the numerical size of the time difference. |
| Space | O(1) extra | The conversion variables, answer, and four-element increment list use constant working memory. The returned integer is the required output and is not counted; the bound remains constant for every valid time. |
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int convertTime(string current, string correct) {
auto toMinutes = [](const string& time) {
return stoi(time.substr(0, 2)) * 60 + stoi(time.substr(3, 2));
};
int difference = toMinutes(correct) - toMinutes(current);
int operations = 0;
vector<int> increments = {60, 15, 5, 1};
for (int increment : increments) {
operations += difference / increment;
difference %= increment;
}
return operations;
}
};The two lines inside the loop form the greedy core. The quotient counts all operations of the current size that fit, while the remainder becomes the only work left for smaller increments. Processing 60 before 15, 5, and 1 is essential: if a smaller increment were used first, the code could spend several operations on minutes that one larger operation would have covered.