inttrap(vector<int>& height){ int len = height.size(); if (len < 3) return0; int max_left[len], max_right[len]; max_left[0] = height[0]; max_right[len-1] = height[len-1]; for (int i = 1; i < len-1; ++i) max_left[i] = max(max_left[i-1], height[i-1]); for (int i = len-2; i >= 0; --i) max_right[i] = max(max_right[i+1], height[i+1]);
int result = 0; for (int i = 1; i < len-1; ++i){ int min_height = min(max_left[i], max_right[i]); if (height[i] < min_height) result = result+min_height-height[i]; } return result; }
inttrap(vector<int>& height){ int len = height.size(); int result = 0, current = 0; stack<int> index; while (current < len){ while (!index.empty() && height[current]>height[index.top()]){ int tmp_h = height[index.top()]; index.pop(); if (index.empty()) break; int distance = current-index.top()-1; int min_h = min(height[current], height[index.top()]); result += distance*(min_h-tmp_h); } index.push(current); ++current; } return result; }