Bank app~15 min2s · 256 MBtarget O(n + years) time, O(years) spaceclassic twin: lc-1854difference-array
A bank app keeps the history of its accounts. Each account has a year when it opened and a year when it closed. An account is active in its opening year and in every later year until the year it closed. It is not active in the closing year.
The bank wants to know the year with the most active accounts, to plan an anniversary report. If several years tie, the bank wants the earliest.
The history covers the years 1900 to 2100, and it holds up to 200,000 accounts.
Write busiest_year(accounts).
accounts[i] is [opened, closed] with 1900 <= opened < closed <= 2100.i is active in the years opened to closed - 1, both included.Input: accounts = [[1950, 1960], [1955, 1965], [1958, 1962], [1990, 2000]]
Output: 1958Write +1 in each opening year and -1 in each closing year. A running total gives the active accounts.
| Year | Note | Active accounts after |
|---|---|---|
| 1950 | +1 | 1 |
| 1955 | +1 | 2 |
| 1958 | +1 | 3 |
| 1960 | -1 | 2 |
| 1962 | -1 | 1 |
| 1965 | -1 | 0 |
| 1990 | +1 | 1 |
| 2000 | -1 | 0 |
The highest count is 3, first reached in 1958. Years without a note keep the count of the year before.
Input: accounts = [[2000, 2001], [2005, 2006]]
Output: 2000Two years tie with 1 active account. The earliest wins.
Input: accounts = [[1900, 2100]]
Output: 1900One account, active in every year.
1 ≤ accounts.length ≤ 200,000 (accounts in the history)1900 ≤ opened < closed ≤ 2100 (years)There are only 201 years, so a change list with one entry for each year is tiny.
Counting the active accounts of each year by scanning all accounts costs 201 × 200,000, about 4 × 10^7 steps. Two notes for each account and one pass over the years cost about 4 × 10^5 steps.