Topic Analysis: (link)
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 .
Subscribe to see which companies asked this question
Problem Solving Ideas:
O (n^2) code is very good to write, the following is the copy of the O (n) Problem solving ideas:
Original address: http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
1 classSolution {2 Public:3 intLargestrectanglearea (vector<int>&height) {4stack<int>Cache;5 intresult =0;6Height.push_back (0);7 for(inti =0; I <height.size ();) {8 if(Cache.empty () | | height[i] >=height[cache.top ()]) {9Cache.push (i++);Ten}Else { One intindex =cache.top (); A Cache.pop (); - intmuliply = Cache.empty ()? I:i-Cache.top ()-1; -result = Max (result, Height[index] *muliply); the } - } - - returnresult; + } -};
[Leetcode] Largest Rectangle in histogram