classSolution{publicintlargestRectangleArea(int[] heights){int res =0;// 單調(diào)棧:存儲(chǔ) indexDeque<Integer> stack =newArrayDeque<>();// 前后添加0:處理邊界,讓heights[0], heights[len - 1] 都可以參與比較(參考恒遞增情況)int[] newHeights =newint[heights.length +2];for(int i =1; i < heights.length +1; i++){newHeights[i]= heights[i -1];}// O(n):遍歷新數(shù)組for(int i =0; i < newHeights.length; i++){// 棧不為空,且當(dāng)前棧頂更大(出現(xiàn)遞減情況)時(shí)while(!stack.isEmpty()&& newHeights[stack.peek()]> newHeights[i]){int index = stack.pop();// 用于獲取當(dāng)前高int l = stack.peek();// 獲取左邊第一個(gè)比當(dāng)前列矮的下標(biāo)int r = i;// 右邊第一個(gè)比當(dāng)前列矮的下標(biāo)// 計(jì)算:以stack.pop()為高,可行的最大矩形res =Math.max(res,(r - l -1)* newHeights[index]);}// 加入當(dāng)前下標(biāo)(此時(shí)保持遞增)stack.push(i);}return res;}}
無注釋版
classSolution{publicintlargestRectangleArea(int[] heights){int res =0;Deque<Integer> stack =newArrayDeque<>();int[] newHeights =newint[heights.length +2];for(int i =1; i < heights.length +1; i++){newHeights[i]= heights[i -1];}for(int i =0; i < newHeights.length; i++){while(!stack.isEmpty()&& newHeights[stack.peek()]> newHeights[i]){int index = stack.pop();int l = stack.peek();int r = i;res =Math.max(res,(r - l -1)* newHeights[index]);}stack.push(i);}return res;}}
二刷
單調(diào)棧,只能說 Dalao 思路還是強(qiáng)
classSolution{publicintlargestRectangleArea(int[] heights){int[] newHeights =newint[heights.length +2];for(int i =1; i <= heights.length; i++){newHeights[i]= heights[i -1];}Deque<Integer> stack =newArrayDeque<>();int max =0;for(int i =0; i < newHeights.length; i++){// 當(dāng)前棧頂為最高列的可行值while(!stack.isEmpty()&& newHeights[i]< newHeights[stack.peek()]){int now = stack.poll();int left = stack.peek();// 左邊第一個(gè)比 now 對應(yīng)值小的下標(biāo)int right = i;// 當(dāng)前即是右邊第一個(gè)比 now 對應(yīng)值小的下標(biāo)max =Math.max(max,(right - left -1)* newHeights[now]);// 維護(hù) max}// 棧中比當(dāng)前大的都去掉了,now 可以加入棧,并保持單調(diào)增了。stack.push(i);}return max;}}