Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created May 16, 2021 03:43
Show Gist options
  • Save CarlaTeo/a613a6a7a49beefd2414819946e81f2c to your computer and use it in GitHub Desktop.
Save CarlaTeo/a613a6a7a49beefd2414819946e81f2c to your computer and use it in GitHub Desktop.
[JS] Given list of births and deaths find year with most people alive
// Given list of births and deaths find year with most people alive (in case of tie return any)
function maxPopulation(yearsOfBirthNDeath) {
const populationChange = [];
yearsOfBirthNDeath.forEach(([birth, death]) => {
if(populationChange[birth]) populationChange[birth] += 1;
else populationChange[birth] = 1;
const yearAfterDeath = death + 1;
if(populationChange[yearAfterDeath]) populationChange[yearAfterDeath] -= 1;
else populationChange[yearAfterDeath] = -1;
})
let maxPeople = 0;
let currentPeople = 0;
let yearWithMaxPeople = null;
populationChange.forEach( (populationDelta, year) => {
currentPeople += populationDelta;
if(currentPeople > maxPeople) {
maxPeople = currentPeople;
yearWithMaxPeople = year;
}
});
return [yearWithMaxPeople, maxPeople];
}
// ------------------------------------------- Test --------------------------------------------//
let years = [[2000, 2005], [2007, 2021], [2010, 2030], [2020,2021], [2020, 2036]];
// Each dotted sequence represents a person life span; we can see which years are the same by looking at starts and/or ends that align
// ----- --------
// ---
// -------
// -------
console.log(maxPopulation(years)); // [2020, 4]
years = [[2000, 2005], [2007, 2021]];
console.log(maxPopulationYear(years)); // [2000, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment