当前位置:网站首页>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;
}
}
边栏推荐
- 比亚迪、长城混动市场再“聚首”
- Take you to API development by hand
- [Jianzhi offer] 57 - ii Continuous positive sequence with sum s
- How to delete a specific line from a text file using the SED command?
- 定义一个结构体Fraction,表示分数,用于表示 2/3, 5/6这样的分数
- Hands on in-depth learning notes (XIV) 3.7 Simple implementation of softmax regression
- 2022 love analysis · panoramic report of digital manufacturers of state-owned enterprises
- Thread pool: the most common and error prone component of business code
- Static program analysis (I) -- Outline mind map and content introduction
- Build your own website (23)
猜你喜欢
What material is sa537cl1? Sa537cl1 corresponds to the national standard material
What material is sa537cl2? Analysis of mechanical properties of American standard container plate
[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
What material is sa537cl2 equivalent to in China? Sa537cl2 corresponding material
QT serial port UI design and solution to display Chinese garbled code
2022.02.14_ Daily question leetcode five hundred and forty
关于学习Qt编程的好书精品推荐
Fast Ethernet and Gigabit Ethernet: what's the difference?
Why is WPA3 security of enterprise business so important?
Static program analysis (I) -- Outline mind map and content introduction
随机推荐
消息队列消息丢失和消息重复发送的处理策略
arduino-esp32:LVGL项目(一)整体框架
Network security web penetration technology
浅谈拉格朗日插值及其应用
What material is sa537cl2 equivalent to in China? Sa537cl2 corresponding material
MySQL user management
What material is 12cr1movr? Chemical property analysis of pressure vessel steel plate 12cr1movr
什么是质押池,如何进行质押呢?
[combinatorics] polynomial theorem (polynomial coefficients | full arrangement of multiple sets | number of schemes corresponding to the ball sub model | polynomial coefficient correlation identity)
Hong Kong Polytechnic University | data efficient reinforcement learning and adaptive optimal perimeter control of network traffic dynamics
Execute script unrecognized \r
PHP production website active push (website)
Atom QT 16_ audiorecorder
CC2530 common registers
How to allow remote connection to MySQL server on Linux system?
What material is sa537cl2? Analysis of mechanical properties of American standard container plate
线程池:业务代码最常用也最容易犯错的组件
(补)双指针专题
C语言按行修改文件
29:第三章:开发通行证服务:12:开发【获得用户账户信息,接口】;(使用VO类包装查到的数据,以符合接口对返回数据的要求)(在多处都会用到的逻辑,在Controller中可以把其抽成一个共用方法)