sir any kind of hint for siolving this problem
Sir any kind of hint for siolving this problem
hey @Harsh_Sonwani
Method 1: This is a simple solution to the above problem.
- 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.
-
Algorithm:
- Traverse the array from start to end.
- For every element, traverse the array from start to that index and find the maximum height (a) and traverse the array from the current index to end and find the maximum height (b) .
- The amount of water that will be stored in this column is min(a,b) – array[i] , add this value to total amount of water stored
- Print the total amount of water stored.
If you are not able to write a code. I will help
Try yourself first
Best Approach
Use the two pointer approach. Loop from index 0 to the end of the given array. If a wall greater than or equal to the previous wall is encountered then make note of the index of that wall in a var called prev index. Keep adding previous wall’s height minus the current (ith) wall to the variable water. Have a temporary variable that stores the same value as water. If no wall greater than or equal to the previous wall is found then quit. If prev index < size of the input array then subtract the temp variable from water, and loop from end of the input array to prev_index and find a wall greater than or equal to the previous wall (in this case, the last wall from backwards).