2409. Count Days Spent Together

2023. 1. 7. 20:34Algorithm/Leetcode, Lintcode, HackerRank, etc.

    목차
반응형

Intuition

this problem is easy. so, the day of arrive and leave are limited in the same year!
so, simplely find out the leave day of the year and the arrive day of the year for both Alice and Bob.
And then find the latest arrive day and the earliest leave day.
If the leave day is bigger than or equal to the arrive day, then just calculate difference between leave day and arrive day. that's the answer.

Complexity

  • Time complexity:
    maximum time for calculation is 12 x 4 = 48
    it means that the algorithm has constant time complexity.
    That is O(1)
  • Space complexity:
    O(1) as well

Code

class Solution:
    def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
        month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        def get_day_of_year(info):
            to_month = int(info.split('-')[0]) - 1
            to_day = int(info.split('-')[1])

            cnt = 0
            month = 0
            while month < to_month:
                cnt += month_days[month]
                month += 1

            cnt += to_day
            return cnt

        alice_start = get_day_of_year(arriveAlice)
        se = get_day_of_year(leaveAlice)

        bs = get_day_of_year(arriveBob)
        be = get_day_of_year(leaveBob)

        start = max(alice_start, bs)
        end = min(se, be)

        days = 0
        if start <= end:
            days = end - start + 1

        return days


반응형