Coding Challenge – Find the year with the most number of people alive!

Question: Given a list of people with their birth and end years (all between 1900 and 2000), find the year with the most number of people alive.

Input:

[{ 'by': 1990, 'dy': 1992 }, { 'by': 1995, 'dy': 1999 }, { 'by': 1992, 'dy': 2000 }, { 'by': 1990, 'dy': 1996 }]

Output: 1995

Solution: To solve this problem first we will create the year array which adds up with people birth year and reduce by 1 with death year.

We will loop through the new array and keep adding population and if the population is higher than previous year then use that year as most number of people alive.

Let’s use that dynamic programming algorithm into actual code!

const maxPopulation = (peoplearr) => {
  let yearArr = new Array(11).fill(0);
  for (let i = 0; i < peoplearr.length; i++) {
    yearArr[peoplearr[i].by - 1990] += 1;
    yearArr[peoplearr[i].dy - 1990] -= 1;
  }
  let pop = 0;
  let maxpop = 0;
  let maxYear = 0
  for (let j = 0; j < yearArr.length; j++) {
    pop += yearArr[j];
    if (maxpop < pop) {
      maxpop = pop;
      maxYear = j;
    }
  }
  return 1990 + maxYear;
}

let people = [{ 'by': 1990, 'dy': 1992 }, { 'by': 1995, 'dy': 1999 }, { 'by': 1992, 'dy': 2000 }, { 'by': 1990, 'dy': 1996 }];

console.log(maxPopulation(people));