Monitoring~15 min2s · 256 MBtarget O(m) time, O(1) spacecomplexity · prefix-sums
A monitoring system summarises metric series. For each series it builds a prefix table, which has one entry more than the series has readings. Each entry takes a fixed number of bytes. The series are already in memory, so only the tables are extra.
A job either frees each table before it starts the next series, or keeps all tables until the end. The team wants the peak extra memory of both ways, without running them.
Write peak_extra_bytes(lengths, width, free_after_use).
lengths[i] is the number of readings of series i. The series are processed in order.i has lengths[i] + 1 entries of width bytes each, and it is allocated when the series is processed.free_after_use is 1, the table is freed before the next series starts. If it is 0, every table is kept until the end.Input: lengths = [3, 5, 2], width = 8, free_after_use = 1
Output: 48The tables have 4, 6 and 3 entries, so 32, 48 and 24 bytes. Each is freed before the next, so the peak is the largest table.
| Series | Entries | Bytes | Live after allocating |
|---|---|---|---|
| 0 | 4 | 32 | 32 |
| 1 | 6 | 48 | 48 |
| 2 | 3 | 24 | 24 |
The peak is 48 bytes.
Input: lengths = [3, 5, 2], width = 8, free_after_use = 0
Output: 104The same tables are kept, so the live bytes add up: 32, then 80, then 104. The peak is 104.
Input: lengths = [], width = 4, free_after_use = 0
Output: 0With no series nothing is allocated, so the peak is 0.
0 ≤ lengths.length ≤ 100,000 (series)0 ≤ lengths[i] ≤ 1,000,000,000 (readings in a series)1 ≤ width ≤ 64 (bytes for each table entry)free_after_use is 0 or 1Building the tables entry by entry would take up to 10^14 steps. The peak can pass 2 × 10^9 bytes, so use 64-bit integers. Compute each table's size once, from its length.