Topic description
There is a histogram, represented by an array of integers, where the width of each column is 1, and the maximum rectangular area contained by the given histogram is obtained. For example, for the histogram [2,7,9,4], the maximum rectangle it contains is 14 (that is, the 7x2 rectangle that [7,9] includes).
Given a histogram a and its total width of n, return the maximum rectangular area. Ensure that the histogram width is less than or equal to 500. Ensure the result is within the range of int.
Test sample: [2,7,9,4,1],5
Return: 14
The popular solution on the internet is to use a monotone incremental stack, which records the subscript of the column instead of the height, and the stack always maintains such a relationship: Stack[i] The first height on the left is less than the subscript for stack[i-1]. To maintain this nature you need to do some work on the stack: if the stack is empty or the height of the stack column is not less than the height of the top column of the stack, go directly into the stack. There is no doubt that this will meet the above requirements; If the height of the stack column is less than the height of the top column of the stack, so that the direct into the stack will break the relationship, so you need to pop out of the stack, and then calculate the maximum size of this column can be composed of rectangular area: Assuming that the current stack column subscript I, according to the This rectangle must not be more than stack[i-1], not to the right of the current into the Stack column subscript K (because the current into the stack column is the right first occurrence height is less than the top column of the stack). This computes the number of columns between stack[i-1] and K and then multiply the height of the stack column by the maximum rectangular area of the stack column, and then compare it to the maximum value of the current record. If the stack top column is still larger than the stack column, loop through the above operation until the stack is empty or the height of the stack column is not less than the height of the top column of the stack.
The code is as follows:
import java.util.*; public class Maxinnerrec {public int countarea (int[] A, int n) {linkedlist<integer> stack = new Linked
List<> ();
int result = Integer.min_value;
for (int i = 0; I <= a.length ++i) {int h = i = = a.length? 0:a[i];
if (Stack.isempty () | | | h >= a[stack.peek ()]) {Stack.push (i);
else{int height = Stack.pop ();
result = Math.max (result, A[height] * (Stack.isempty () i:i-Stack.peek ()-1));
i--;
} return result; }
}