Leetcode 1854. Maximum Population Year
The problem is from LeetCode: “1854. Maximum Population Year.”
You are given a 2D integer array logs
where each logs[i] = [birth_i, death_i]
indicates the birth and death years of the ith person.
The population of some year x
is the number of people alive during that year. A person is considered alive during the year x
if birth_i <= x < death_i
. Note that the person is not alive during the year of their death.
Return the year with the maximum population. If there are multiple years with the same maximum population, return the smallest such year.
Input: logs = [[1993, 1999], [2000, 2010]]
Output: 1993
Explanation: The maximum population is 1, and 1993 is the earliest year with this population.
Q:
What is the range of years we should consider?
A:
All years in the logs. Generally, the problems consider years within a reasonable human lifespan.
Q:
Are the birth and death years inclusive?
A:
A person is considered alive during the year of birth and up to but not including the year of death.
Q:
How large can the input be?
A:
Logs are typically reasonably small due to constraints in competitive programming. Let’s assume n
(number of logs) to be in the range of 1 <= n <= 100
.
Steps:
population_changes
, large enough to cover all possible years given in the logs.#include <vector>
#include <algorithm>
using namespace std;
int maxPopulationYear(vector<vector<int>>& logs) {
const int START_YEAR = 1950;
const int END_YEAR = 2050;
vector<int> population_changes(END_YEAR - START_YEAR + 1, 0);
for(const auto& log : logs) {
population_changes[log[0] - START_YEAR]++;
population_changes[log[1] - START_YEAR]--;
}
int max_population = 0;
int max_population_year = START_YEAR;
int current_population = 0;
for(int year = START_YEAR; year <= END_YEAR; ++year) {
current_population += population_changes[year - START_YEAR];
if(current_population > max_population) {
max_population = current_population;
max_population_year = year;
}
}
return max_population_year;
}
n
is the number of logs, and (end_year - start_year)
is the range from 1950 to 2050. Since the range is constant, this simplifies to O(n).This approach is efficient and accommodates the provided constraints gracefully.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?