Minimum Number of Taps to Open to Water a Garden
Problem Description
There is a one-dimensional garden on the x-axis from 0 to n. There are n+1 taps located at x = 0, 1, ..., n.
ranges[i] means the tap at position i can water [i - ranges[i], i + ranges[i]].
Return the minimum number of taps needed to water the entire garden [0, n], or -1 if impossible.
Pattern: Greedy (same as Jump Game II / LC 45). Convert each tap to an interval, then greedily extend as far as possible at each step.
Optimization: Build maxReach[l] = farthest right endpoint for intervals starting at l. Then scan left to right greedily.
Example 1:
Input: n = 5, ranges = [3,4,1,1,0,0]
Output: 1
Explanation: Tap at 1 (range 4) covers [0,5] — entire garden.
Example 2:
Input: n = 3, ranges = [0,0,0,0]
Output: -1
Example Test Cases
Example 1
Input: [5,[3,4,1,1,0,0]]
Expected: 1
Example 2
Input: [3,[0,0,0,0]]
Expected: -1
Example 3
Input: [7,[1,2,1,0,2,1,0,1]]
Expected: 3
Run your code to see the results