Skip to content

Commit

Permalink
feat(line-sweep,prefix): Add 1854
Browse files Browse the repository at this point in the history
  • Loading branch information
euchangxian committed Dec 18, 2024
1 parent 72083ed commit f92f5f1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
41 changes: 41 additions & 0 deletions C++/1854-MaximumPopulationYear/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <cstddef>
#include <cstdlib>
#include <map>
#include <vector>

class Solution {
public:
int maximumPopulation(std::vector<std::vector<int>>& logs) {
// logs[i] = [birth, death], birth/death year of the ith person.
// population is the number of people alive during that year.
// i-th person is counted in year x population if x is in the inclusive
// range [birth, death-1],
// Want: earliest year with the maximum population.
// Line Sweep.
// Events are the birth/death years. If birth, add 1 to the prefix sum,
// if death, -1. Take the max of the sum.

// {year, count}
std::map<int, int> events;
for (const auto& log : logs) {
int birth = log[0];
int death = log[1];

++events[birth];
--events[death];
}

int maxPop = 0;
int maxYear = 0;

int pop = 0;
for (const auto [year, count] : events) {
pop += count;
if (pop > maxPop) {
maxPop = pop;
maxYear = year;
}
}
return maxYear;
}
};
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,7 @@ Now solving in C++. Like it.
| 1823 | FindTheWinnerOfTheCircularGame | [![C++](assets/c++.svg)](C++/1823-FindTheWinnerOfTheCircularGame/Solution.cpp) |
| 1829 | MaximumXORForEachQuery | [![C++](assets/c++.svg)](C++/1829-MaximumXORForEachQuery/Solution.cpp) |
| 1845 | SeatReservationManager | [![C++](assets/c++.svg)](C++/1845-SeatReservationManager/Solution.cpp) |
| 1854 | MaximumPopulationYear | [![C++](assets/c++.svg)](C++/1854-MaximumPopulationYear/Solution.cpp) |
| 1857 | LargestColorValueInADirectedGraph | [![C++](assets/c++.svg)](C++/1857-LargestColorValueInADirectedGraph/Solution.cpp) |
| 1861 | RotatingTheBox | [![C++](assets/c++.svg)](C++/1861-RotatingTheBox/Solution.cpp) |
| 1863 | SumOfAllSubsetXORTotals | [![C++](assets/c++.svg)](C++/1863-SumOfAllSubsetXORTotals/Solution.cpp) |
Expand Down

0 comments on commit f92f5f1

Please sign in to comment.