please explain other approach than brute force for rainwater harvesting
Rain water harvesting
-
Approach: The idea is to traverse every array element and find the highest bars on the left and right sides. Take the smaller of two heights. The difference between the smaller height and height of the current element is the amount of water that can be stored in this array element.
you must pre-compute the highest bar on the left and right of every bar in linear time. Then use these pre-computed values to find the amount of water in every array element. -
Algorithm:
- Create two arrays left and right of size n. create a variable max_ = INT_MIN .
- Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = max_
- Update max_ = INT_MIN.
- Run another loop from end to start. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign right[i] = max_
- Traverse the array from start to end.
- The amount of water that will be stored in this column is min(a,b) – array[i] ,(where a = left[i] and b = right[i]) add this value to total amount of water stored
- Print the total amount of water stored.
Reference Code
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.