Leetcode 1854. Maximum Population Year
The problem “Maximum Population Year” requires us to determine the year between 1950 and 2050 that has the maximum population. We are given an array of logs
where logs[i] = [birthi, deathi]
indicates the birth and death years of the i-th person. The population includes the year of birth but not the year of death.
Requirements:
logs
be?
logs
array.populationChange
with a size corresponding to the year range (e.g., index 0 for 1950 and index 100 for 2050).log
entry [birthi, deathi]
, increment the array at the index representing birthi
and decrement the array at the index representing deathi
.populationChange
array to get the population for each year.public class Solution {
public int maximumPopulation(int[][] logs) {
int[] populationChange = new int[101]; // From 1950 to 2050, hence 101 elements
for (int[] log : logs) {
int birth = log[0];
int death = log[1];
populationChange[birth - 1950]++;
if (death <= 2050) {
populationChange[death - 1950]--;
}
}
int maxPopulation = 0;
int maxYear = 1950;
int currentPopulation = 0;
for (int year = 0; year < 101; year++) {
currentPopulation += populationChange[year];
if (currentPopulation > maxPopulation) {
maxPopulation = currentPopulation;
maxYear = 1950 + year;
}
}
return maxYear;
}
}
The time complexity of this solution is (O(n + m)) where:
Thus, this solution is linear relative to the number of entries, making it very efficient for the given constraints.
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?