leetcode do question notes 84 the largest rectangle in the histogram

Given  n  non-negative integers, used to represent the height of each column in the histogram. Each column 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.

Idea 1: Monotonic stack

int largestRectangleArea(int* heights, int heightsSize){
    int top = -1;
    int area, i;
    int maxarea = 0;
    int *stack = (int *)malloc(sizeof(int) * (heightsSize + 2));
    int *buff = (int *)malloc(sizeof(int) * (heightsSize + 2));

    buff[0] = 0;
    for (int i = 1; i <= heightsSize; i++) {
        buff[i] = heights[i - 1];
    }
    buff[heightsSize + 1] = 0;

    stack[++top] = 0;
    for (i = 1; i < heightsSize + 2; i++) {
        while (top > 0 && buff[i] < buff[stack[top]]) {
            area = (i - stack[top - 1] - 1) * buff[stack[top]];
            maxarea = maxarea > area ? maxarea : area;
            top--;
        }
        stack[++top] = i;
    }
    return maxarea;
}

analyze:

This question uses the characteristics of the monotonic stack. There are two methods. One is to recurse directly from the middle number to the left and right to determine whether the answer is monotonically increasing or decreasing. The second is to add an extra space and judge whether it is monotone from the leftmost or rightmost Increment or decrement, this method sets up an extra space, uses the characteristic of the monotone stack to monotonically decrease to the left to find the minimum value, calculate the maximum value of the rectangle, and finally output the answer.

Summarize:

This question examines the relevant knowledge of monotone stacks, uses monotone decreasing recursion to find the minimum value, calculates the size of the rectangle, and finally returns the maximum value

Guess you like

Origin blog.csdn.net/si_mple_/article/details/132349801