Given n non-negative integers representing the histogram ' s bar height where the width of each bar is 1, find the Area of largest rectangle in the histogram.
Above is a histogram the where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, and which has an area = 10
unit.
For example,
Given height = [2,1,5,6,2,3]
,
Return 10
.
Train of thought: This problem still has some difficulty, just start to think of double hands, front and back scan, but each time to find the smallest height of time all need to traverse once, efficiency is not very high. Is O (N2).
The code is as follows:
public class Solution {public int largestrectanglearea (int[] height) {int max = 0;//max value int i = 0;/ /left pointer int j = height.length-1;//Right pointer boolean isminchange = TRUE; Double pointer scan while (i <= j) {int minheight = integer.max_value;//Range Minimum if (isminchange) {//min value changed Isminchange = false; Re-get minimum value for (int k = i; k <= j;k++) {if (Height[k] < MinHeight) {m Inheight = Height[k]; }}}//Area int. = (j-i + 1) *minheight; if (Max < area) {max = area; } if (i = = j) {//If equal, end break; } if (Height[i] < Height[j]) {//The left pointer is incremented until the current greater than int k = i; while (k <= J && Height[k] <= Height[i]) {if (height[k] = = MinHeight) {//Determine if the minimum value changes Isminc Hange = true; } k++; } i = k; }else{//right pointer decreases until greater than current int k = j; while (k >= i && height[k] <= height[j]) {if (height[k] = = MinHeight) {//Determine if the minimum value changes Ismin Change = true; } k--; } j = k; }} return max; }}
Solution on the OJ, so can only see the information on the Internet, finally found the following, is a stack to solve.
public class Solution {public int largestrectanglearea (int[] height) {if (height = = NULL | | height.length = = 0) re Turn 0; stack<integer> stheight = new stack<integer> (); stack<integer> Stindex = new stack<integer> (); int max = 0; for (int i = 0; i < height.length; i++) {if (Stheight.isempty () | | height[i] > Stheight.peek ()) { Stheight.push (Height[i]); Stindex.push (i); }else if (Height[i] < Stheight.peek ()) {int lastIndex = 0; while (!stheight.isempty () && Height[i] < Stheight.peek ()) {LastIndex = Stindex.pop (); int area = Stheight.pop () * (I-lastindex); if (Max < area) {max = area; }} stheight.push (Height[i]); Stindex.push (LastIndex); }} while (!stheight.isempty ()) {int area = Stheight.pop () * (height.length-Stindex.pop ()); max = Max < area? Area:max; }return Max; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 84.Largest Rectangle in histogram (maximum rectangular histogram) thinking and method of solving problems