classSolution { public: inttrap(vector<int> &height){ int n = height.size(); int *maxLessThan = newint[n]; int *maxGreaterThan = newint[n]; maxLessThan[0] = 0; maxGreaterThan[n - 1] = 0;
int curMax = 0; for (int i = 1; i < n; ++i) { if (height[i - 1] > curMax) curMax = height[i - 1]; maxLessThan[i] = curMax; } curMax = 0; for (int i = n - 2; i >= 0; --i) { if (height[i + 1] > curMax) curMax = height[i + 1]; maxGreaterThan[i] = curMax; }
int ret = 0; for (int i = 0; i < n; ++i) { int t = std::min(maxLessThan[i], maxGreaterThan[i]); int capa = t > height[i] ? t - height[i] : 0; ret += capa; }