mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0084.柱状图中最大的矩形.md
添加单调栈精简java代码
This commit is contained in:
@ -307,6 +307,33 @@ class Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
单调栈精简
|
||||
```java
|
||||
class Solution {
|
||||
public int largestRectangleArea(int[] heights) {
|
||||
int[] newHeight = new int[heights.length + 2];
|
||||
System.arraycopy(heights, 0, newHeight, 1, heights.length);
|
||||
newHeight[heights.length+1] = 0;
|
||||
newHeight[0] = 0;
|
||||
|
||||
Stack<Integer> stack = new Stack<>();
|
||||
stack.push(0);
|
||||
|
||||
int res = 0;
|
||||
for (int i = 1; i < newHeight.length; i++) {
|
||||
while (newHeight[i] < newHeight[stack.peek()]) {
|
||||
int mid = stack.pop();
|
||||
int w = i - stack.peek() - 1;
|
||||
int h = newHeight[mid];
|
||||
res = Math.max(res, w * h);
|
||||
}
|
||||
stack.push(i);
|
||||
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python3:
|
||||
|
||||
|
Reference in New Issue
Block a user