Minimum Taps to Open to Water a Garden

There is a one-dimensional garden from point 0 to point n. You are given an integer n and an array ranges where ranges[i] describes the coverage radius of the ith tap positioned at i. Return the minimum number of taps to open so that the entire garden is watered, or -1 if it is impossible. Pattern focus: Jump Game. Convert each tap into a reachable interval and greedily expand the farthest coverage, similar to jumping through segments.

Input Format

n = garden length, ranges = tap coverage radii

Output Format

minimum number of taps required, or -1 if impossible

Constraints

  • 1 <= n <= 10^4
  • ranges.length = n + 1
  • 0 <= ranges[i] <= 10^4

Examples

Example 1:

Input:

n = 5
ranges = [3,4,1,1,0,0]

Output:

1

Explanation:

The tap at position 1 covers the entire garden.

Example 2:

Input:

n = 3
ranges = [0,0,0,0]

Output:

-1

Explanation:

No tap can cover any positive length of the garden.

Example 3:

Input:

n = 7
ranges = [1,2,1,0,2,1,0,1]

Output:

3

Explanation:

Three taps are sufficient to cover the whole garden.

Loading...
Minimum Taps to Open to Water a Garden - Greedy