i am not able to get the logic pls help
I am not able to get the logic
you need to use a stack,
push the index of the first element of the array into the stack
now for each element in the array
store the top of stack as top
and pop the element
while(arr[s.top()] < arr[i])
calculate distance as i - s.top() - 1. why? consider just two buildings one at index 2 and other at index 0, so water trapped between them is obviously 1 unit and hence i - s.top() - 1
now u need the current water in it for that take the min height between arr[i] and arr[s.top()] and subtract arr[top], top is the first building of this iteration, arr[i] is the current building and arr[s.top()] is the previously smaller building, min is taken because that is the max height the water can reach, udate top as s.top() and pop the element
ans will be ans += minheight*distance
after the end of the loop push the index into the stack
hey, you are using an entirely wrong approach, it will only be applicable to few specific cases. try the approach (stack based) that i have mentioned above
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.