2409. Count Days Spent Together

LeetCode 力扣

1. Description

Alice and Bob make separate business trips to Rome. Their stays are described by arriveAlice, leaveAlice, arriveBob, and leaveBob, with both arrival and departure days included.
Each date uses five characters in the format “MM-DD”, specifying a month and day. All four dates belong to the same non-leap year.
Return how many calendar days both people are in Rome.
The month lengths, from January through December, are [31,28,31,30,31,30,31,31,30,31,30,31].

2. Example

Example 1

Input: arriveAlice = “08-15”, leaveAlice = “08-18”, arriveBob = “08-16”, leaveBob = “08-19”
Output: 3
Explanation: Their stays overlap on August 16, 17, and 18, giving three days together.

Example 2

Input: arriveAlice = “10-01”, leaveAlice = “10-31”, arriveBob = “11-01”, leaveBob = “12-31”
Output: 0
Explanation: Alice leaves before Bob arrives, so their stays do not overlap.

3. Constraints

  • Each date is a five-character string formatted as “MM-DD”.
  • Each person’s arrival is on or before their departure.
  • All dates are valid and belong to the same non-leap year.

4. Solutions

Date Conversion

Time complexity: O(1)
Space complexity: O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    int to_day(const string &date) {
        static constexpr int prefix_days[] = {
            0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};

        int month = stoi(date.substr(0, 2));
        int day = stoi(date.substr(3, 2));

        return prefix_days[month - 1] + day;
    }

public:
    int countDaysTogether(
        const string &alice_arrive,
        const string &alice_leave,
        const string &bob_arrive,
        const string &bob_leave) {

        int arrive = to_day(max(alice_arrive, bob_arrive));
        int leave = to_day(min(alice_leave, bob_leave));

        return max(0, leave - arrive + 1);
    }
};
comments powered by Disqus