当前位置:网站首页>The largest matrix (H) in a brush 143 monotone stack 84 histogram
The largest matrix (H) in a brush 143 monotone stack 84 histogram
2022-07-03 16:57:00 【Tang and Song Dynasties】
subject :
Given n Nonnegative integers , It is used to indicate the height of each column in the histogram . Each column is adjacent to each other , And the width is 1 .
In this histogram , The maximum area of a rectangle that can be outlined .
--------------------------
Input :heights = [2,1,5,6,2,3]
Output :10
explain : The largest rectangle is the red area in the figure , Area is 10
Input : heights = [2,4]
Output : 4
Tips :
1 <= heights.length <=105
0 <= heights[i] <= 104
--------------------
reflection :
This topic and 42. Rainwater collection , Are two topics that echo each other from afar , All suggestions should be done carefully ,
There are many similarities in principle , But there are differences in details , It can deepen the understanding of monotone stack !
Dynamic programming :
The writing method of dynamic planning of this topic is the overall idea and 42. It is consistent to receive rainwater , But more than 42. It's harder to catch rain .
The difficulty lies in recording each column The first one on the left is smaller than the subscript of the column , Instead of the first one on the left less than the height of the column .
So you need to cycle through , That is, the following is used in the process of searching while, Please see the following notes for details ,
Sorting out ideas in problem solving :42. Rainwater collection Has been introduced in .
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
vector<int> minLeftIndex(heights.size());
vector<int> minRightIndex(heights.size());
int size = heights.size();
// Record each column The first one on the left is smaller than the subscript of the column
minLeftIndex[0] = -1; // Note here that initialization , Prevent the following while Dead cycle
for (int i = 1; i < size; i++) {
int t = i - 1;
// This is not for if, But the process of constantly looking to the left
while (t >= 0 && heights[t] >= heights[i]) t = minLeftIndex[t];
minLeftIndex[i] = t;
}
// Record each column The first one on the right is smaller than the subscript of the column
minRightIndex[size - 1] = size; // Note here that initialization , Prevent the following while Dead cycle
for (int i = size - 2; i >= 0; i--) {
int t = i + 1;
// This is not for if, But the process of constantly looking to the right
while (t < size && heights[t] >= heights[i]) t = minRightIndex[t];
minRightIndex[i] = t;
}
// Sum up
int result = 0;
for (int i = 0; i < size; i++) {
int sum = heights[i] * (minRightIndex[i] - minLeftIndex[i] - 1);
result = max(sum, result);
}
return result;
}
};
Monotonic stack :
The solution of local monotone stack and the problem of receiving rainwater echo each other from afar .
Why do you say that ,42. Rainwater collection Is to find the first column on the left and right sides of each column that is greater than the height of the column ,
And this problem is to find the first column smaller than the column on the left and right sides of each column .
Here we come to the important properties of monotone stack , Is the order in the monotone stack , Is it from small to large or from large to small .
In the problem solution 42. Rainwater collection In, I explained the monotonous stack of rainwater from the top of the stack ( Elements pop up from the top of the stack ) The order to the bottom of the stack should be from small to large .
Then, because this problem is to find the first column smaller than the column on the left and right sides of each column , So from the top of the stack ( Elements pop up from the top of the stack )
The order to the bottom of the stack should be from large to small !
Let me give you an example , Pictured :
Only the order from big to small in the stack , To ensure that the top element of the stack finds the first column on the left and right that is smaller than the top element of the stack .
So the order of this monotonous stack is just the opposite of that of receiving rain .
At this time, you should find that it is actually
To the top of the stack and
The next element at the top of the stack and
The three elements to be stacked form the height and width of the maximum area we require
Understand this , I have a good grasp of monotone stack .
Except that the order of elements in the stack is different from that of rainwater , The rest of the logic is almost the same ,
In the problem solution 42. I have explained all aspects of monotonous stack in detail , I won't repeat it here .
The rest is to analyze the following three situations :
Situation 1 : Current traversal elements heights[i] Less than the top of the stack element heights[st.top()] The situation of
Situation two : Current traversal elements heights[i] Equal to the top element of the stack heights[st.top()] The situation of
Situation three : Current traversal elements heights[i] Greater than the top element of the stack heights[st.top()] The situation of
-----------------
Code :
Dynamic programming :
class Solution {
public int largestRectangleArea(int[] heights) {
int length = heights.length;
int[] minLeftIndex = new int[length];
int[] maxRightIndex = new int[length];
// Record the first subscript on the left that is smaller than the column
minLeftIndex[0] = -1;
for (int i = 1; i < length; i++) {
int t = i - 1;
// This is not for if But the national policy of constantly looking to the right
while (t >= 0 && heights[t] >= heights[i]) t = minLeftIndex[t];
minLeftIndex[i] = t;
}
// Record each column The first one on the right is smaller than the subscript of the column
maxRightIndex[length - 1] = length;
for (int i = length - 2; i >= 0; i--) {
int t = i + 1;
while (t < length && heights[t] >= heights[i]) t = maxRightIndex[t];
maxRightIndex[i] = t;
}
// Sum up
int result = 0;
for (int i = 0; i < length; i++) {
int sum = heights[i] * (maxRightIndex[i] - minLeftIndex[i] - 1);
result = Math.max(sum, result);
}
return result;
}
}
Monotonic stack :
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<>();
// Array capacity , Add an element to the head and tail
int[] newHeights = new int[heights.length + 2];
newHeights[0] = 0;
newHeights[newHeights.length - 1] = 0;
for (int index = 0; index < heights.length; index++) {
newHeights[index + 1] = heights[index];
}
heights = newHeights;
stack.push(0);
int result = 0;
// The first element is already on the stack , From the subscript 1 Start
for (int i = 1; i < heights.length; i++) {
// Be careful heights[i] Is and heights[stack.pop()] Compare stack.pop() It's a subscript
if (heights[i] > heights[stack.peek()]) {
stack.push(i);
}else if (heights[i] == heights[stack.peek()]) {
stack.pop();// This can be added , Can not add , The effect is the same , Different ideas
stack.push(i);
}else {
while (heights[i] < heights[stack.peek()]) {
// Note that while
int mid = stack.peek();
stack.pop();
int left = stack.peek();
int right = i;
int w = right - left - 1;
int h = heights[mid];
result = Math.max(result, w * h);
}
stack.push(i);
}
}
return result;
}
}
边栏推荐
- [sword finger offer] 58 - I. flip the word order
- LeetCode 1656. Design ordered flow
- ucore概述
- 汇编实例解析--实模式下屏幕显示
- C语言按行修改文件
- Why is WPA3 security of enterprise business so important?
- RF Analyze Demo搭建 Step by Step
- PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
- [combinatorics] polynomial theorem (polynomial theorem | polynomial theorem proof | polynomial theorem inference 1 item number is the number of non negative integer solutions | polynomial theorem infe
- Alibaba P8 painstakingly sorted it out. Summary of APP UI automated testing ideas. Check it out
猜你喜欢
MySQL converts comma separated attribute field data from column to row
Shentong express expects an annual loss of nearly 1billion
Aike AI frontier promotion (7.3)
CC2530 common registers for watchdog
斑马识别成狗,AI犯错的原因被斯坦福找到了
CC2530 common registers for crystal oscillator settings
Atom QT 16_ audiorecorder
Why is WPA3 security of enterprise business so important?
【Try to Hack】主动侦查隐藏技术
CC2530 common registers for serial communication
随机推荐
NLP four paradigms: paradigm 1: fully supervised learning in the era of non neural networks (Feature Engineering); Paradigm 2: fully supervised learning based on neural network (Architecture Engineeri
RF Analyze Demo搭建 Step by Step
A survey of state of the art on visual slam
[combinatorics] recursive equation (example 1 of recursive equation | list recursive equation)
On Lagrange interpolation and its application
Golang anonymous function use
Idea configuration plug-in
13mnnimo5-4 German standard steel plate 13MnNiMo54 boiler steel 13MnNiMo54 chemical properties
[combinatorics] non descending path problem (number of non descending paths with constraints)
Depth first search of graph
Static program analysis (I) -- Outline mind map and content introduction
Redis:关于列表List类型数据的操作命令
Web crawler knowledge day03
New features of C 10
Central South University | through exploration and understanding: find interpretable features with deep reinforcement learning
CC2530 common registers for ADC single channel conversion
The most complete postman interface test tutorial in the whole network, API interface test
How programming apes grow rapidly
远程办公之如何推进跨部门项目协作 | 社区征文
[combinatorics] recursive equation (constant coefficient linear homogeneous recursive equation | constant coefficient, linear, homogeneous concept description | constant coefficient linear homogeneous