84. 柱状图中最大的矩形
参考灵神一步步优化:从三次遍历到一次遍历(Python/Java/C++/C/Go/JS/Rust)
思路
这题的思路比较精妙,使用的是单调栈。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public int largestRectangleArea(int[] heights) { int n = heights.length; Deque<Integer> st = new ArrayDeque<>(); st.push(-1); int ans = 0; for (int right = 0; right <= n; right++) { int h = right < n ? heights[right] : -1; while (st.size() > 1 && h <= heights[st.peek()]) { int i = st.pop(); int left = st.peek(); ans = Math.max(ans, heights[i] * (right - left - 1)); } st.push(right); } return ans; } }
|