代码随想录算法训练营-day60-84.柱状图中最大的矩形

84.柱状图中最大的矩形

  1. 学习文章链接:
  2. 思路:接雨水的单调栈是从小到大,那么柱状图就是从大到小。
  3. 代码:
class Solution {
    public int largestRectangleArea(int[] heights) {
        int len = heights.length;
        int[] newHeigths = new int[len + 2];
        int size = newHeigths.length;
        newHeigths[0] = 0;
        newHeigths[size - 1] = 0;
        for(int i = 0; i < len; i++){
            newHeigths[i + 1] = heights[i];
        }
        Stack<Integer> st = new Stack<>();
        int result = 0;
        st.push(0);
        for(int i = 1; i < size; i++){
            if(newHeigths[i] > newHeigths[st.peek()]){
                st.push(i);
            }else if(newHeigths[i] == newHeigths[st.peek()]){
                st.pop();
                st.push(i);
            }else{
                while(!st.isEmpty() && newHeigths[i] < newHeigths[st.peek()]){
                    int mid = st.peek();
                    st.pop();
                    int left = st.peek();
                    int right = i;
                    int sum = (right - left - 1) * newHeigths[mid];
                    result = Math.max(sum, result);
                }
                st.push(i);
            }
        }
        return result;
    }
}

你可能感兴趣的:(代码随想录算法训练营,算法,数据结构,leetcode)