image.png

    1. class Solution {
    2. public:
    3. int largestRectangleArea(vector<int>& heights) {
    4. if(!heights.size()) return 0;
    5. heights.push_back(0);
    6. heights.insert(heights.begin(), 0);
    7. int n = heights.size();
    8. vector<int> dp(n);
    9. stack<int> idx; //要增 一到变小了,就要把前面的都弄掉了
    10. int res = 0;
    11. for(int i = 0; i < n; i++)
    12. {
    13. while(idx.size() && heights[i] < heights[idx.top()])
    14. {
    15. auto tmp = idx.top();
    16. idx.pop();
    17. res = max(res, (i - idx.top() - 1) * heights[tmp]);
    18. }
    19. idx.push(i);
    20. }
    21. return res;
    22. }
    23. };

    第二次写题
    用dp的原因是,这个高度只能是柱子的高度,然后就是要去计算区间的长度;
    这里要注意的就是这个区间的长度怎么计算

    1. class Solution {
    2. public:
    3. int largestRectangleArea(vector<int>& heights) {
    4. heights.insert(heights.begin(), -1);
    5. heights.push_back(-1);
    6. vector<int> v = vector<int>(heights.size(), 0);
    7. stack<int> stk; //存的是idx
    8. for(int i = 0; i < heights.size(); i++)
    9. {
    10. while(stk.size() && heights[stk.top()] > heights[i])
    11. {
    12. int idx = stk.top();
    13. stk.pop();
    14. v[idx] = heights[idx] * (i - stk.top() - 1);
    15. }
    16. stk.push(i);
    17. }
    18. int res = 0;
    19. for(int i = 0; i < heights.size() - 1; i++)
    20. res = max(res, v[i]);
    21. return res;
    22. }
    23. };