[LeetCode][42. Trapping Rain Water] From Brute Force to DP to Two Pointers with Detail Explaination
By Long Luo
This article is the solution From Brute Force to DP to Two Pointers with Detail Explaination of Problem 42. Trapping Rain Water .
Intuition

It’s like Leetcode 11. Container With Most Water , we can consider the black block as a wall, the blue block as water. Given an array, each element represents the height of the wall from left to right, find out how many units of water can be held.
The solution can be refered 2 Approaches: BF and Two Pointers with Image Explaination .
1. Brute Force
It’s easy to use the brute force approach. The time complexity is \(O(max^n)\) , so it will TLE.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33// Row time: O(max * n) space: O(1)
// TLE
public static int trap_row(int[] height) {
if (height == null || height.length <= 2) {
return 0;
}
int ans = 0;
int len = height.length;
int maxHeight = 0;
for (int x : height) {
maxHeight = Math.max(maxHeight, x);
}
for (int i = 1; i <= maxHeight; i++) {
boolean flag = false;
int water = 0;
for (int j = 0; j < len; j++) {
if (flag && height[j] < i) {
water++;
}
if (height[j] >= i) {
ans += water;
water = 0;
flag = true;
}
}
}
return ans;
}
Analysis
- Time Complexity: \(O(max^n)\)
- Space Complexity: \(O(1)\)