1255. Enough Coverage Day

Medium3.5 points estimatedPrefix SumBinary SearchArray3 hints

A water network has positions 0..need.length - 1, all holding 0 units at the start, and position i is satisfied once it holds at least need[i] units. On day d (0-based) the pump event ops[d] = [l, r, v] adds v units to every position from min(l, r) to max(l, r), inclusive.

Return the smallest t from 0 to ops.length such that, after applying only the first t events ops[0..t-1], at least m positions are satisfied; t = 0 means no event is applied. If this never happens, return -1. Since v is never negative, a satisfied position never becomes unsatisfied, so binary search on t and check each candidate with a difference array. Aim for O((n + q) log q) time and O(n) space.

Example 1

Input:
need = [3,0,5], ops = [[0,1,2],[1,2,3],[2,0,2]], m = 2
Output:
3
Explanation:

After 0, 1 and 2 events only position 1 is satisfied (values 0,0,0 then 2,2,0 then 2,5,3), but after all 3 events the values are 4, 7, 5 and every position is satisfied, so t = 3.

Example 2

Input:
need = [5,5], ops = [[0,1,1],[0,1,1]], m = 1
Output:
-1
Explanation:

Positions reach at most 2 units, below the need of 5, so no position is ever satisfied and the answer is -1.

Example 3

Input:
need = [0,0,4], ops = [[2,2,4]], m = 3
Output:
1
Explanation:

Two positions are satisfied from the start, and the single event satisfies the third, so t = 1.

Constraints

1 ≤ need.length ≤ 1000; 1 ≤ ops.length ≤ 1000; 0 ≤ l, r < need.length; 0 ≤ v ≤ 105; 0 ≤ need[i] ≤ 109; 1 ≤ m ≤ need.length.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O((n + q) log q)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…