Skip to content

2409. Count Days Spent Together 👎

  • Time: $O(1)$
  • Space: $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
25
26
27
28
29
class Solution {
 public:
  int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob,
                        string leaveBob) {
    const int arriveA = toDays(arriveAlice);
    const int leaveA = toDays(leaveAlice);
    const int arriveB = toDays(arriveBob);
    const int leaveB = toDays(leaveBob);
    int ans = 0;

    for (int day = 1; day <= 365; ++day)
      if (arriveA <= day && day <= leaveA && arriveB <= day && day <= leaveB)
        ++ans;

    return ans;
  }

 private:
  const vector<int> days{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

  int toDays(const string& s) {
    const int month = (s[0] - '0') * 10 + (s[1] - '0');
    const int day = (s[3] - '0') * 10 + (s[4] - '0');
    int prevDays = 0;
    for (int m = 1; m < month; ++m)
      prevDays += days[m];
    return prevDays + day;
  }
};
 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
class Solution {
  public int countDaysTogether(String arriveAlice, String leaveAlice, String arriveBob,
                               String leaveBob) {
    final int arriveA = toDays(arriveAlice);
    final int leaveA = toDays(leaveAlice);
    final int arriveB = toDays(arriveBob);
    final int leaveB = toDays(leaveBob);
    int ans = 0;

    for (int day = 1; day <= 365; ++day)
      if (arriveA <= day && day <= leaveA && arriveB <= day && day <= leaveB)
        ++ans;

    return ans;
  }

  private final int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

  private int toDays(final String s) {
    final int month = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0');
    final int day = (s.charAt(3) - '0') * 10 + (s.charAt(4) - '0');
    int prevDays = 0;
    for (int m = 1; m < month; ++m)
      prevDays += days[m];
    return prevDays + day;
  }
}
 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
class Solution:
  def countDaysTogether(
      self,
      arriveAlice: str,
      leaveAlice: str,
      arriveBob: str,
      leaveBob: str,
  ) -> int:
    days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    def toDays(s: str) -> int:
      month = int(s[:2])
      day = int(s[3:])
      prevDays = 0
      for m in range(1, month):
        prevDays += days[m]
      return prevDays + day

    arriveA = toDays(arriveAlice)
    leaveA = toDays(leaveAlice)
    arriveB = toDays(arriveBob)
    leaveB = toDays(leaveBob)
    ans = 0

    for day in range(1, 366):
      if arriveA <= day and day <= leaveA and arriveB <= day and day <= leaveB:
        ans += 1

    return ans