Skip to content

Commit 4543aa4

Browse files
Merge pull request youngyangyang04#2043 from asxy/asxy-patch-2
柱状图中最大的矩形添加java精简代码
2 parents ccf4089 + fca3050 commit 4543aa4

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

problems/0084.柱状图中最大的矩形.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,33 @@ class Solution {
307307
}
308308
}
309309
```
310+
单调栈精简
311+
```java
312+
class Solution {
313+
public int largestRectangleArea(int[] heights) {
314+
int[] newHeight = new int[heights.length + 2];
315+
System.arraycopy(heights, 0, newHeight, 1, heights.length);
316+
newHeight[heights.length+1] = 0;
317+
newHeight[0] = 0;
318+
319+
Stack<Integer> stack = new Stack<>();
320+
stack.push(0);
321+
322+
int res = 0;
323+
for (int i = 1; i < newHeight.length; i++) {
324+
while (newHeight[i] < newHeight[stack.peek()]) {
325+
int mid = stack.pop();
326+
int w = i - stack.peek() - 1;
327+
int h = newHeight[mid];
328+
res = Math.max(res, w * h);
329+
}
330+
stack.push(i);
331+
332+
}
333+
return res;
334+
}
335+
}
336+
```
310337

311338
Python3:
312339

0 commit comments

Comments
 (0)