LeetCode 2409: Count Days Spent Together Solution

Master LeetCode problem 2409 (Count Days Spent Together), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2409. Count Days Spent Together

Problem Explanation

Explanation:

To solve this problem, we can find the overlap between the ranges of dates that Alice and Bob are in Rome. We can do this by first determining the maximum of the arrival dates and the minimum of the leaving dates for Alice and Bob, and then finding the number of days in the overlap.

  1. Find the maximum of the arrival dates for Alice and Bob, and the minimum of the leaving dates for Alice and Bob.
  2. Calculate the number of days in the overlap by finding the difference between the minimum leaving date and the maximum arrival date, and adding 1 (inclusive).

Solution Code

class Solution {
    public int countDays(String arriveAlice, String leaveAlice, String arriveBob, String leaveBob) {
        int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        String[] aliceArrive = arriveAlice.split("-");
        String[] aliceLeave = leaveAlice.split("-");
        String[] bobArrive = arriveBob.split("-");
        String[] bobLeave = leaveBob.split("-");

        int maxArrive = Math.max(Integer.parseInt(aliceArrive[0]) * 100 + Integer.parseInt(aliceArrive[1]), Integer.parseInt(bobArrive[0]) * 100 + Integer.parseInt(bobArrive[1]));
        int minLeave = Math.min(Integer.parseInt(aliceLeave[0]) * 100 + Integer.parseInt(aliceLeave[1]), Integer.parseInt(bobLeave[0]) * 100 + Integer.parseInt(bobLeave[1]));

        int overlapDays = Math.max(0, minLeave - maxArrive + 1);

        return overlapDays;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2409 (Count Days Spent Together)?

This page provides optimized solutions for LeetCode problem 2409 (Count Days Spent Together) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2409 (Count Days Spent Together)?

The time complexity for LeetCode 2409 (Count Days Spent Together) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2409 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2409 in Java, C++, or Python.

Back to LeetCode Solutions