Minimum Lights to Illuminate a Road Problem
Description
LeetCode Problem 3964.
You are given an integer array lights of length n, representing positions 0 through n - 1 on a road.
For each position i:
- If
lights[i] = v, wherev > 0, there is a working bulb at positionithat illuminates every position frommax(0, i - v)tomin(n - 1, i + v), inclusive. - If
lights[i] = 0, there is no working bulb at positioni.
A position is visible if it is illuminated by at least one working bulb.
You may install additional bulbs at any positions. Each additional bulb installed at position j illuminates positions from max(0, j - 1) to min(n - 1, j + 1), inclusive.
Return the minimum number of additional bulbs required to make every position on the road visible.
Example 1:
Input: lights = [0,0,0,0]
Output: 2
Explanation:
One optimal placement is:
- Install an additional bulb at position 1, illuminating positions [0, 1, 2].
- Install an additional bulb at position 3, illuminating positions [2, 3].
Therefore, the minimum number of additional bulbs required is 2.
Example 2:
Input: lights = [0,0,0,2,0]
Output: 1
Explanation:
- Since lights[3] = 2, the working bulb at position 3 illuminates positions [1, 2, 3, 4].
- Installing an additional bulb at position 1 illuminates positions [0, 1, 2], making every position visible.
- Therefore, the minimum number of additional bulbs required is 1.
Constraints:
1 <= n == lights.length <= 10^50 <= lights[i] <= n
Solution
Approach: Difference Array + Prefix Sum
A working bulb at i with strength v > 0 lights the range [max(0, i - v), min(n - 1, i + v)]. Mark all these ranges with a difference array (add 1 at the start, subtract 1 just after the end) and take prefix sums: a position is lit when its prefix sum is positive.
What remains are maximal runs of dark positions. A new bulb lights 3 consecutive positions, and it can be placed freely, so a run of length len needs ceil(len / 3) = (len + 2) / 3 new bulbs, independently of the other runs. Add that up over all runs.
Complexity: time O(n), space O(n).
class Solution:
def minLights(self, lights: List[int]) -> int:
n = len(lights)
d = [0] * n
for i, v in enumerate(lights):
if v > 0:
l = max(0, i - v)
r = min(n - 1, i + v)
d[l] += 1
if r + 1 < n:
d[r + 1] -= 1
s = cnt = 0
ans = 0
for x in d:
s += x
if s == 0:
cnt += 1
else:
ans += (cnt + 2) // 3
cnt = 0
ans += (cnt + 2) // 3
return ans