Count Days Spent Together
The problem is about finding the total number of days that Alice and Bob are in Rome together. Given their respective arrival and departure dates, the code needs to calculate this overlap.
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
| class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
# Days in each month
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Function to convert date to the total number of days from the start of the year
def date_to_days(date: str) -> int:
month, day = map(int, date.split("-"))
total_days = 0
for i in range(month - 1):
total_days += days_in_month[i]
total_days += day - 1
return total_days
arriveAlice_days = date_to_days(arriveAlice)
leaveAlice_days = date_to_days(leaveAlice)
arriveBob_days = date_to_days(arriveBob)
leaveBob_days = date_to_days(leaveBob)
# Find the overlapping days
overlap_start = max(arriveAlice_days, arriveBob_days)
overlap_end = min(leaveAlice_days, leaveBob_days)
# If there is an overlap, calculate the number of days
if overlap_start <= overlap_end:
return overlap_end - overlap_start + 1
else:
return 0
|
The function date_to_days
converts the given date to the total number of days from the start of the year. This helps in easily comparing the arrival and departure dates for both Alice and Bob. Then we find the start and end of their overlap, and if there is an overlap, we calculate and return the number of days. Otherwise, we return 0.