Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Time Difference in C++
Suppose we have a list of 24-hour clock time points in "Hour:Minutes" format, we have to find the minimum minutes difference between any two time points in the list. So if the input is like [“12:30”,”15:17”], so this will return 167.
To solve this, we will follow these steps −
- Define an array called ok of size 24*60 + 1, and initially all are false.
- n := size of tp
- for i in range 0 to n – 1
- hr := the hour part from the time
- min := minute part of the string
- time := hr * 60 + min
- if ok[time] is true, then return 0, otherwise set ok[time] as true.
- last := 0, first := inf, ret := inf, prev := -inf
- for i in range 0 to 24*60
- if ok[i] is true, then
- last := max of i, last
- first := min of i and first
- if prev is not –inf, then ret := min of ret and last – prev
- prev := i
- if ok[i] is true, then
- return minimum of ret and 24*60+first-last.
Let us see the following implementation to get better understanding &mnus;
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findMinDifference(vector<string>& tp) {
vector <bool> ok(24 * 60 + 1, false);
int n = tp.size();
for(int i = 0; i < n; i++){
int hr = stoi(tp[i].substr(0, 2));
int min = stoi(tp[i].substr(3, 2));
int time = hr * 60 + min;
if(ok[time]) return 0;
ok[time] = true;
}
int last = 0;
int first = INT_MAX;
int ret = INT_MAX;
int prev = INT_MIN;
for(int i = 0; i <= 24 * 60; i++){
if(ok[i]){
last = max(i, last);
first = min(i, first);
if(prev != INT_MIN) ret = min(ret, last - prev);
prev = i;
}
}
return min(ret, 24 * 60 + first - last);
}
};
main(){
vector<string> v = {"12:30","15:17"};
Solution ob;
cout << (ob.findMinDifference(v));
}
Input
["12:30","15:17"]
Output
167
Advertisements