Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2043 from asxy/asxy-patch-2
Browse files Browse the repository at this point in the history
柱状图中最大的矩形添加java精简代码
  • Loading branch information
youngyangyang04 authored May 1, 2023
2 parents ccf4089 + fca3050 commit 4543aa4
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions problems/0084.柱状图中最大的矩形.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down

0 comments on commit 4543aa4

Please sign in to comment.