Minimum Number Of Taps To Water Garden
Posted: 12 Nov, 2020
The gardener wants to water the garden by opening the minimum number of taps. The garden is one-dimensional along the x-axis of length N i.e. the garden starts from point 0 and ends at point N. There are N + 1 tap located at points [0, 1, 2, …, N] in the garden.
You are given an integer N, and an array named “ranges” of size N + 1(0-indexed). The ith tap, if opened, can water the gardener from point (i - ranges[i]) to (i + ranges[i]) including both. The task is to find the minimum number of taps that should be open to water the whole garden, return -1 if the garden can not be watered.
Can you solve the problem in O(N) time?
The first line contains a single integer T representing the number of test cases. The first line of each test case will contain the integer N. The second and the last line of each test case will contain N single space-separated integers representing the elements of the array “ranges”.
Output format :
For each test case, print a single integer representing the value of the minimum number of taps needed to open by the gardener to fill the whole garden.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10 1 <= N <= 10^4 0 <= ranges[i] <= 100 Time Limit: 1 sec
- The idea to approach the problem is to convert the Ranges array into a list of intervals and sort them.
- As we need to choose minimum taps so at first we will find the farthest tap which we will choose so that it will cover the 0th coordinate and after choosing this coordinate we will update the leftmost coordinate with the right of the current chosen tap. This will act as the left boundary for the remaining taps to cover. Also increment the tap count to be returned.
- Now we repeat the above 2nd step until we cover all the possible coordinates(when we reach a tap which will cover a range more than equal to the last coordinate of the garden) or if there is no possible tap left that can cover the leftmost updated coordinate.
Count Numbers Containing Given Digit K Times
Posted: 20 Apr, 2022
Count Numbers With Equal First and Last Digit
Posted: 20 Apr, 2022
Angels vs Devils
Posted: 5 May, 2022
Max Non Adjacent sum
Posted: 10 May, 2022
Mario And His Princess
Posted: 12 May, 2022