LeetCode 2409: Count Days Spent Together
LeetCode 2409 Solution 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.
- Find the maximum of the arrival dates for Alice and Bob, and the minimum of the leaving dates for Alice and Bob.
- 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).
LeetCode 2409 Solutions in Java, C++, Python
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;
}
}
Interactive Code Editor for LeetCode 2409
Improve Your LeetCode 2409 Solution
Use the editor below to refine the provided solution for LeetCode 2409. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...