max_reach
of size n + 1
to store the maximum reach for each position.max_reach
with the rightmost position each tap can reach.taps
to 0, curr_end
to 0, and next_end
to 0.i
.
i
is greater than next_end
, return -1 (the garden cannot be watered).i
is greater than curr_end
, increment taps
and update curr_end
to next_end
.next_end
with the maximum of its current value and max_reach[i]
.taps
as the minimum number of taps needed.