What is the error in code it is failing if of the cases
hello @sneha23
ur solution time complexity is O(n^2).
try to solve this in O(n) .
-
Approach: The idea is to traverse every array element and find the highest bars on 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.
To make this efficient one 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 array 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.
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.