File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -23,7 +23,12 @@ public int largestRectangleArea(int[] heights) {
2323 return max ;
2424 }
2525
26- /** 注意栈中的是index,不是高度
26+ /**
27+ * 核心思路是用栈保存一个高度递增的index,当出现一个局部最高点时,计算以该最高点为高度的最大面积
28+ * 该局部最高点的形成可能是新加的柱子较矮,也可能是随着旧的高点不断出栈导致的
29+ * 该局部高点的特点是"相邻的柱子都比他高",这里相邻的意思是左边延伸到下一个出栈的index,右边延伸到新加的柱子
30+ *
31+ * 注意栈中的是index,不是高度
2732 * 栈保持递增,当出现小于栈顶的元素时,意味着可以计算栈顶可以延伸的矩形面积了
2833 * 其左边界是次栈顶,右边界是当前元素
2934 */
Original file line number Diff line number Diff line change @@ -4,18 +4,28 @@ public class Main {
44
55 public static class Solution {
66
7- public int leastInterval (char [] tasks , int n ) {
8- int [] count = new int [26 ];
9- for (char c : tasks ) {
10- count [c - 'A' ]++;
7+ public int largestRectangleArea (int [] heights ) {
8+ int [] indexes = new int [heights .length + 1 ];
9+ int top = -1 , max = 0 ;
10+
11+ for (int i = 0 ; i <= heights .length ; ) {
12+ int height = i == heights .length ? 0 : heights [i ];
13+ if (top < 0 || height > heights [indexes [top ]]) {
14+ indexes [++top ] = i ++;
15+ } else {
16+ int k = heights [indexes [top --]];
17+ int left = top < 0 ? 0 : (indexes [top ] + 1 );
18+ max = Math .max (max , (i - 1 - left + 1 ) * k );
19+ }
1120 }
12- Arrays .sort (count );
13- int i = 25 ;
14- for ( ; i >= 0 && count [i ] == count [25 ]; i --);
15- return Math .max (tasks .length , (count [25 ] - 1 ) * (n + 1 ) + 25 - i );
21+
22+ return max ;
1623 }
24+
1725 }
1826
27+
28+
1929 public static void main (String [] args ) {
2030 Solution solution = new Solution ();
2131 }
You can’t perform that action at this time.
0 commit comments