#!/jcode/lang/cpp https://xitu.github.io/jcode-languages/dist/lang-cpp.json

/*height = [5,0,2,1,4,0,1,0,3]  
输出：17  
解析：上面是由数组 [5,0,2,1,4,0,1,0,3] 表示的柱子高度，在这种情况下，可以接 17 个单位的青豆。*/
#include<iostream>
#include <vector>
#include <stack>
using namespace std;

//单调栈思想
//看做三个柱子构成的凹槽，单调栈从尾部到栈头，从大到小
int fun(vector<int> height){
    stack<int> st;
    if(height.size() <= 2) return 0;
    //st存放索引
    st.push(0);
    int ans = 0;
    for(int i = 1; i < height.size(); i++){
      int num = height[i];
      while(!st.empty() && num > height[st.top()]){
          //num 为右边界，top()为中间，第二个栈顶元素为左边界
          //mid 为索引位置
          int mid = st.top();
          st.pop();
          if(!st.empty()){
              int h = min(num, height[st.top()]) - height[mid];
              int w = i - st.top() - 1;
              ans += (h * w);
          }
         
      }
       st.push(i);
    }
    return ans;
}
int main() {
    vector<int> height = {5,0,2,1,4,0,1,0,3};
    cout<<fun(height)<<endl;
  return 0;
}