LeetCode 1854: Maximum Population Year Solution

Master LeetCode problem 1854 (Maximum Population Year), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1854. Maximum Population Year

Problem Explanation

Explanation

To solve this problem, we can iterate over each year in the range of birth and death years provided in the logs. We maintain a count of the population for each year by incrementing for births and decrementing for deaths. Finally, we find the year with the maximum population.

  • We create an array population to store the population count for each year.
  • We iterate over each entry in the logs array, incrementing the population count for birth year and decrementing for the year before the death year.
  • After processing all entries, we find the year with the maximum population count.

Time complexity: O(n) where n is the number of entries in the logs array. Space complexity: O(1) since we are using a fixed-size array to store population counts for each year.

Solution Code

class Solution {
    public int maximumPopulation(int[][] logs) {
        int[] population = new int[2051];
        for (int i = 0; i < logs.length; i++) {
            population[logs[i][0]]++;
            population[logs[i][1]]--;
        }
        
        int maxPopulation = 0;
        int maxYear = 0;
        int currentPopulation = 0;
        
        for (int i = 1950; i <= 2050; i++) {
            currentPopulation += population[i];
            if (currentPopulation > maxPopulation) {
                maxPopulation = currentPopulation;
                maxYear = i;
            }
        }
        
        return maxYear;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1854 (Maximum Population Year)?

This page provides optimized solutions for LeetCode problem 1854 (Maximum Population Year) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1854 (Maximum Population Year)?

The time complexity for LeetCode 1854 (Maximum Population Year) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1854 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1854 in Java, C++, or Python.

Back to LeetCode Solutions