42. Trapping Rain Water
Intuition
For this question, we should note that the height of water in height[i] is determined by the minimum of its "left maximum" and "right maximum"
res[i] = Math.max(lmax[i], rmax[i]) - height[i]
Solution 1
Use array lmax and rmax to store the "left maximum" and "right maximum" for each index and iterate the height array to get the total volumn.
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(N)\)
Code
Solution 2
Use two pointers to store the left maximum and right maximum. This approach optimize the space complexity.
lmax<rmax: we can learn that on the "left part", the height of water must be determined bylmax-
Similarly, if
lmax>=rmax, we can conclude that on the "right part", the height of water must be determined byrmax
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(1)\)