Thursday, August 31st
Water Taps
Given the locations and ranges of water taps in a 1-dimensional garden, determine the minimum number of taps required to water the garden
This problem can be solved in a greedy manner by organizing taps based on their reach
First create a vector to store the maximum reaches of taps
Then for each tap, determine its left and rightmost reach, minding limits of the garden. Then, for each starting position, use the maxReach vector and the max() function to store the maximum reach of sprinklers beginning from the give start
Then initiate the greedy solution by initializing variables to count the number of taps, store the rightmost position reached, and the next endpoint
For the meat of the program. Minding the initiation of the variables above, iterate from i=0 to n. If i is greater than nextEnd, return -1. Otherwise, if I is greater than currEnd, increment the number of taps and spade currEnd to nextEnd. Finally, set nextEnd to the max of itself and its entry in maxReach. This allows us to select taps based on furthest reach right.
Finally, return the number of taps
A challenging dynamic programming problem with a sensible greedy approach
Thanks to the Editorial for a clear, concise, and well-commented solution
Comments
Post a Comment