
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
Find Maximum Possible Smallest Time Gap Between Two Clock Readings in C++
Suppose we have an array D with N elements. Consider in a code festival there are N+1 participants including Amal. Amal checked and found that the time gap between the local times in his city and the i-th person's city was D[i] hours. The time gap between two cities: For any two cities A and B, if the local time in city B is d o'clock at the moment when the local time in city A is 0 o'clock, then the time gap between these two cities is minimum of d and 24−d hours.
Here, we are using 24-hour notation. Then, for each pair of two people chosen from the N+1 people, he wrote out the time gap between their cities. Let the smallest time gap among them be s hours. We have to find the maximum possible value of s.
So, if the input is like D = [7, 12, 8], then the output will be 4, because the time gap between the second and third persons' cities is 4 hours.
Steps
To solve this, we will follow these steps −
n := size of D sort the array D Define an array t insert 0 at the end of t for initialize i := 0, when i < n, update (increase i by 1), do: if i mod 2 is same as 0, then: insert D[i] at the end of t Otherwise insert 24 - D[i] at the end of t sort the array t ans := inf for initialize i := 1, when i < size of t, update (increase i by 1), do: ans := minimum of ans and t[i] - t[i - 1] return ans
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<int> D) { int n = D.size(); sort(D.begin(), D.end()); vector<int> t; t.push_back(0); for (int i = 0; i < n; i++){ if (i % 2 == 0) t.push_back(D[i]); else t.push_back(24 - D[i]); } sort(t.begin(), t.end()); int ans = 1e9; for (int i = 1; i < t.size(); i++){ ans = min(ans, t[i] - t[i - 1]); } return ans; } int main(){ vector<int> D = { 7, 12, 8 }; cout << solve(D) << endl; }
Input
{ 7, 12, 8 }
Output
4