Trapping Rain Water
https://leetcode.com/problems/trapping-rain-water/description/
Thoughts
Code
class Solution {
public int trap(int[] height) {
if (height.length <= 2) {
return 0;
}
int[] lH = new int[height.length];
int[] rH = new int[height.length];
for (int i = 1; i < height.length; i++) {
lH[i] = Math.max(lH[i - 1], height[i - 1]);
}
for (int i = height.length - 2; i >= 0; i--) {
rH[i] = Math.max(height[i + 1], rH[i + 1]);
}
int sum = 0;
for (int i = 0; i < height.length; i++) {
sum += Math.max(0, Math.min(lH[i], rH[i]) - height[i]);
}
return sum;
}
}Analysis
Ver.2
Last updated