#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
int fectchTrap(std::vector<int>& arr) {
int size = arr.size();
int ans;
std::stack<int> st;
for (int idx=0; idx < size; idx ++) {
while(!st.empty() && arr[idx] > arr[st.top()]) {
int top = st.top();
st.pop();
if (st.empty()) {
break;
}
int left = st.top();
int w = idx - left -1;
int h = std::min(arr[left], arr[idx]) - top;
ans += w * h;
}
st.push(idx);
}
return ans;
}
int main(){
std::vector<int> arr{ 4, 1, 2, 3, 5, 6};
int res = fectchTrap(arr);
printf("%d\n", res);
return 1;
}
接雨水算法
于 2023-04-25 15:04:20 首次发布