Ctrl K

Fewest Lawn Sprinklers

Hard
A lawn runs along a line from point 0 to point length. There is a sprinkler at every integer point 0, 1, ..., length, so length + 1 sprinklers in total. When switched on, the sprinkler at point i waters the segment [i - reach[i], i + reach[i]]. Switch on as few sprinklers as possible so that the whole lawn [0, length] gets watered, and return how many you used. If the lawn cannot be watered completely, return -1. Water landing outside the lawn neither helps nor hurts.
Example 1
length=6, reach=[1, 0, 3, 0, 0, 1, 0] → 2

The sprinkler at point 2 waters [-1, 5] and the one at point 5 waters [4, 6]. Together they cover the whole lawn [0, 6]; no single sprinkler is enough.

Example 2
length=4, reach=[1, 0, 0, 0, 1] → -1

Even with everything switched on, the stretch between points 1 and 3 stays dry.

Example 3
length=3, reach=[0, 0, 5, 0] → 1

The sprinkler at point 2 alone reaches from -3 to 7.

Constraints
  • 1 ≤ length ≤ 10⁴
  • len(reach) = length + 1
  • 0 ≤ reach[i] ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Heaviest Reading Day HardFuel Stops Along the Way HardBiggest Number Divisible by Three HardA Round Cake and Two Neighbors HardBest Order for a Tasting Menu Hard
loading Python…
Input
length=6, reach=[1, 0, 3, 0, 0, 1, 0]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.