Largest rectangle in histogram java

Given n non-negative integers, they are used to represent the height of each column in the histogram. Each pillar is adjacent to each other and has a width of 1.

Find the maximum area of ​​the rectangle that can be outlined in the histogram.

The above is an example of a histogram, where the width of each column is 1, and the given height is [2,1,5,6,2,3].

The shaded part in the figure is the largest rectangular area that can be outlined, and its area is 10 units.

Example:

Input: [2,1,5,6,2,3]
Output: 10

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/largest-rectangle-in-histogram The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Idea: I only thought of the violent solution O(n^2) from left to right for this question. I posted it directly after reading the official O(n). The official solution also has two violent solutions, fixed high and fixed Left node.
ps: It doesn’t seem to be sent, send it again

class Solution {
    
    
    public int largestRectangleArea(int[] heights) {
    
    
        int n = heights.length;
        int[] left = new int[n];
        int[] right = new int[n];
        
        Stack<Integer> mono_stack = new Stack<Integer>();
        for (int i = 0; i < n; ++i) {
    
    
            while (!mono_stack.isEmpty() && heights[mono_stack.peek()] >= heights[i]) {
    
    
                mono_stack.pop();
            }
            //最近的小于其的左边的位置 
            left[i] = (mono_stack.isEmpty() ? -1 : mono_stack.peek());
            mono_stack.push(i);
        }

        mono_stack.clear();
        for (int i = n - 1; i >= 0; --i) {
    
    
            while (!mono_stack.isEmpty() && heights[mono_stack.peek()] >= heights[i]) {
    
    
                mono_stack.pop();
            }
            //最近的小于其的右边的位置 
            right[i] = (mono_stack.isEmpty() ? n : mono_stack.peek());
            mono_stack.push(i);
        }
        
        int ans = 0;
        //固定其高度,加上拥有了左右节点
        for (int i = 0; i < n; ++i) {
    
    
            ans = Math.max(ans, (right[i] - left[i] - 1) * heights[i]);
        }
        return ans;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/111750027