You are given an array events where events[i] = [timestamp_i, user_id_i] represents an e-book download at time timestamp_i by user user_id_i. You are also given an integer window_size, the length of a time window.
Find the maximum number of download events that fall within any single window of length window_size. Two events at timestamps t1 and t2 are considered within the same window if |t1 - t2| < window_size. Return the maximum number of concurrent downloads in any such window.
Function Signature
def max_concurrent_downloads(events: list[list[int]], window_size: int) -> int:
Rules
-
A group of events fits in one window when every pair satisfies
|t1 - t2| < window_size
, which is the same as the latest timestamp minus the earliest one being less than
window_size
. In interval terms the window is half-open,
[s, s + window_size)
.
-
Every event counts separately. The user ID does not affect the answer, so two downloads by the same user both count, and several events can share a timestamp.
-
The events may be given in any order.
Constraints
-
1 <= events.length <= 10^5
-
0 <= events[i][0] <= 10^9
-
1 <= events[i][1] <= 10^5
-
1 <= window_size <= 10^9
Examples
Input: events = [[1,101],[2,102],[3,103],[10,104],[11,105],[12,106],[13,107]], window_size = 5
Output: 4
The window [10, 15) holds the 4 events at timestamps 10, 11, 12 and 13. The window [1, 6) holds only 3, and no window can hold both 3 and 10 because 10 - 3 = 7 is not less than 5.
Input: events = [[5,1],[5,2],[5,3],[5,4]], window_size = 1
Output: 4
All 4 events happen at timestamp 5, so every pair differs by 0, which is less than 1. The window [5, 6) holds all of them.
Input: events = [[7,1],[3,2],[5,1],[8,3],[12,2]], window_size = 5
Output: 3
Sorted, the timestamps are 3, 5, 7, 8 and 12, and the largest groups are 3, 5, 7 (7 - 3 = 4) and 5, 7, 8, since 3 and 8 differ by 5, which is not less than 5. User 1 downloads twice and both events count.