Trapping Rain Water
Trapping Rain Water
LeetCode https://leetcode.cn/problems/trapping-rain-water/
DP Method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int trap(int[] height) {
int len = height.length;
int[] leftMax = new int[len];
leftMax[0] = height[0];
for (int i = 1; i < len; i++) {
leftMax[i] = Math.max(leftMax[i-1], height[i]);
}
int[] rightMax = new int[len];
rightMax[len - 1] = height[len - 1];
for (int i = len - 2; i >= 0; i--) {
rightMax[i] = Math.max(rightMax[i + 1], height[i]);
}
int ans = 0;
for (int i = 0; i < len; i++) {
ans += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return ans;
}
}
Complexity
- Time = O(n)
- Space = O(1)
Greedy Method
- Greedy Solution
This post is licensed under CC BY 4.0 by the author.