File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change @@ -228,6 +228,50 @@ class Solution {
228
228
}
229
229
```
230
230
231
+ 单调栈
232
+ ``` java
233
+ class Solution {
234
+ int largestRectangleArea (int [] heights ) {
235
+ Stack<Integer > st = new Stack<Integer > ();
236
+
237
+ // 数组扩容,在头和尾各加入一个元素
238
+ int [] newHeights = new int [heights. length + 2 ];
239
+ newHeights[0 ] = 0 ;
240
+ newHeights[newHeights. length - 1 ] = 0 ;
241
+ for (int index = 0 ; index < heights. length; index++ ){
242
+ newHeights[index + 1 ] = heights[index];
243
+ }
244
+
245
+ heights = newHeights;
246
+
247
+ st. push(0 );
248
+ int result = 0 ;
249
+ // 第一个元素已经入栈,从下表1开始
250
+ for (int i = 1 ; i < heights. length; i++ ) {
251
+ // 注意heights[i] 是和heights[st.top()] 比较 ,st.top()是下表
252
+ if (heights[i] > heights[st. peek()]) {
253
+ st. push(i);
254
+ } else if (heights[i] == heights[st. peek()]) {
255
+ st. pop(); // 这个可以加,可以不加,效果一样,思路不同
256
+ st. push(i);
257
+ } else {
258
+ while (heights[i] < heights[st. peek()]) { // 注意是while
259
+ int mid = st. peek();
260
+ st. pop();
261
+ int left = st. peek();
262
+ int right = i;
263
+ int w = right - left - 1 ;
264
+ int h = heights[mid];
265
+ result = Math . max(result, w * h);
266
+ }
267
+ st. push(i);
268
+ }
269
+ }
270
+ return result;
271
+ }
272
+ }
273
+ ```
274
+
231
275
Python:
232
276
233
277
动态规划
You can’t perform that action at this time.
0 commit comments