[LeetCode] Count Days Spent Together

2409. Count Days Spent Together

Alice and Bob are traveling to Rome for separate business meetings.

You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the format “MM-DD”, corresponding to the month and day of the date.

Return the total number of days that Alice and Bob are in Rome together.

You can assume that all dates occur in the same calendar year, which is not a leap year. Note that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
pair<int,int> parse(string s) {
auto h = s.find('-');
int month = stoi(s.substr(0,h)), day = stoi(s.substr(h+1));
return {month, day};
}
bool larger(string s, int m, int d) {
auto [sm, sd] = parse(s);
if(sm == m) return sd <= d;
return sm <= m;
}
bool smaller(string s, int m, int d) {
auto [sm, sd] = parse(s);
if(sm == m) return d <= sd;
return m <= sm;
}
public:
int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob) {
int res = 0;
vector<int> days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
auto [sm, sd] = parse(arriveAlice);
for(int i = 1; i <= 12; i++) {
for(int j = 1; j <= 31 and j <= days[i-1]; j++) {
if(larger(arriveAlice, i,j) and larger(arriveBob, i, j) and smaller(leaveAlice, i, j) and smaller(leaveBob, i, j)) res++;
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/18/PS/LeetCode/count-days-spent-together/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.