Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
The brute force approach involves iterating over each element in the height array and for each element, calculating the maximum water that can be trapped above it by determining the highest bars to its left and right. This is done in three loops: one for the current index, and two for finding the left and right max bars.
The dynamic programming approach involves precomputing the maximum height to the left and right of each element using separate arrays. This eliminates the need for nested loops, as in the brute force approach.
leftMax and rightMax.leftMax[i] stores the maximum height from the start to index i.rightMax[i] stores the maximum height from index i to the end.leftMax and rightMax arrays used.The two-pointers technique improves upon the dynamic programming solution by using two pointers that traverse the height array from both ends. It uses variables to store current left and right max heights, allowing us to calculate the trapped water more efficiently without additional space.
left at the start and right at the end of the array.leftMax and rightMax for the maximum heights encountered from the left and right, respectively.leftMax and rightMax is smaller.