Problem
-
We’re given an input array of non-negative integers
height
which represent the elevation map below. Each value represents the height of a bar which has a width of 1. -
Our function should return the maximum area of water that can be trapped between the bars.
Example
Approach 1
Visualize the problem
Solve without code
- Look left and right
- If the left pointer’s value is less than the right
- We want the height to be the minimum between two points
- If left is less than right
- increase index
- calculate max value
- and subtract by bar’s value to get the trapped water
- Repeat the same process for right idx
Solve with code
- If height is empty return 0
- Set left and right values
- Set left and right pointers
- Define result variable
- Begin looping through input array
- if
leftMax < rightMax
l+=1
leftMax = max(leftMax, height[l])
res += leftMax - height[l]
- else
repeat the same process but for right idx
- if
Implementation
Complexity Analysis
- Time Complexity:
- Space Complexity: