Files
leetcode/42.trapping-rain-water.java
2025-10-30 14:47:22 +08:00

32 lines
737 B
Java

/*
* @lc app=leetcode id=42 lang=java
*
* [42] Trapping Rain Water
*/
// @lc code=start
class Solution {
public int trap(int[] height) {
int lmax = height[0], rmax = height[height.length-1];
int l = 0, r = height.length-1, cap = 0;
while(l <= r) {
if(lmax < rmax) {
cap += lmax - height[l];
l++;
if(l < height.length) {
lmax = Math.max(lmax, height[l]);
}
} else {
cap += rmax - height[r];
r--;
if(r >=0) {
rmax = Math.max(rmax, height[r]);
}
}
}
return cap;
}
}
// @lc code=end