KatInterview

Find Continuous Peak Resource Load

Greedy & IntervalsAuto-graded · 19 test cases
HardAuto-gradedGreedy & Intervalssweep-lineintervalsarrays

Last updated

Find the maximum aggregate load over a set of half-open intervals and identify the earliest contiguous time window sustaining it.

You are tracking system metrics across multiple tasks. Each task is defined by a triplet [start, end, load], indicating that it contributes load units of resource consumption continuously over the half-open time interval [start, end). That is, the load is active for any time t satisfying start <= t < end.

Your goal is to determine:

  1. The maximum total resource load active at any moment.
  2. The earliest contiguous time interval [peak_start, peak_end) during which this peak load was continuously maintained without dropping.

Rules & Edge Cases

  • Intervals are half-open [start, end): a task starting at time t adds its load at t, while a task ending at t removes its load at t. If one task ends and another starts at the exact same timestamp t, both changes take effect simultaneously at t.
  • If consecutive time segments sustain the peak load without any drop in load in between, they must be merged into one single continuous interval [peak_start, peak_end).
  • If the maximum load occurs across multiple separate time windows, return the interval that starts at the earliest time.
  • If the input task list is empty, return (0, 0, 0).

Return the result as a 3-tuple (peak_load, peak_start, peak_end).

Constraints

  • 0 <= len(tasks) <= 2 * 10^5
  • 0 <= start < end <= 10^9
  • 1 <= load <= 10^9
  • Total load values can exceed standard 32-bit signed integers.

Examples

Example 1

Input: find_peak_memory([[1, 5, 10], [2, 4, 20], [3, 6, 15]])

Output: [45, 3, 4]

Example 2

Input: find_peak_memory([[1, 4, 10], [4, 7, 10], [2, 5, 10]])

Output: [20, 2, 5]

Hints

Hint 1

Consider using a line-sweep (difference array) approach by generating event points for task starts (+load) and task ends (-load).

Hint 2

To handle simultaneous starts and ends at the exact same timestamp without creating fake spikes or dips, aggregate all deltas per timestamp before processing.

Hint 3

Iterate over sorted unique timestamps and keep track of the running load on each interval [t_i, t_{i+1}). Merge consecutive intervals if the running load equals the current maximum.