1758. Demand Points Cover

A city plans lamp posts along a road whose positions are the integers. Block i consists of the integer positions from lefts[i] to lefts[i] + lengths[i] - 1 inclusive, and it needs at least min(needs[i], lengths[i]) lamp posts standing on its positions (the requirement is capped by the number of positions the block has). A single position can hold at most one lamp post, but one lamp post counts for every block containing its position. Return the smallest total number of lamp posts that satisfies all blocks. Blocks may overlap or nest in any way. The intended solution processes blocks by right end, counting posts already placed with a Fenwick tree and placing missing posts as far right as possible, for about O((n + C) log C) time and O(C) space, where C is the largest coordinate. There are up to 10^5 blocks and every number is at most 10^5.

Example 1

Input:
lefts = [0,2,3], lengths = [4,3,3], needs = [2,2,2]
Output:
3
Explanation:

The blocks are [0,3], [2,4] and [3,5], each needing two posts; positions 2, 3 and 4 satisfy all of them and no two positions can, so the answer is 3.

Example 2

Input:
lefts = [5], lengths = [3], needs = [10]
Output:
3
Explanation:

The single interval [5,7] has length 3, so its requirement is capped at 3 and all three positions must be chosen.

Constraints

1 ≤ n = lefts.length = lengths.length = needs.length ≤ 105; 0 ≤ lefts[i] ≤ 105; 1 ≤ lengths[i] ≤ 105; 1 ≤ needs[i] ≤ 105.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 5,600 msC++ 1,400 msJava 2,800 msJavaScript 2,800 msTypeScript 2,800 ms

Expected complexity

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

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…