alg2025/src/8/12/trapping-rain-water.cpp
2025-08-12 20:42:13 +08:00

34 lines
670 B
C++

#include <vector>
using namespace std;
class Solution {
public:
int trap(std::vector<int> &height) {
if (height.size() < 3) {
return 0;
}
int n = height.size();
int l = 0, r = n - 1;
int lmax = 0;
int rmax = 0;
long long totw = 0;
while (l < r) {
lmax = std::max(lmax, height[l]);
rmax = std::max(rmax, height[r]);
if (lmax < rmax) {
totw += lmax - height[l];
l++;
} else {
totw += rmax - height[r];
r--;
}
}
return totw;
}
};
int main() {
}