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 where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
Example:
Input: [2,1,5,6,2,3] Output: 10
//----------------------------------------------错误代码----------------------------------------------------》》》》》》》》》》》》》》》
class Solution { public: int largestRectangleArea(vector<int>& heights) { int i=0; const int n=heights.size()-1; int a[n]; int max; while(i<n){ int temp=i; while(heights[i]<=heights[i+1]){ a[temp]+=heights[temp]; i++; } i++; max=max>a[temp]?max:a[temp]; } return max; } };
class Solution { public: int largestRectangleArea(vector<int>& heights) { int curr_processed_num {NULL}; int largest {0}, curr_area; int size = heights.size(); int expand_left{0}, expand_right{0}; for(int i = 0; i < size; ++i) { if(heights[i] == curr_processed_num) continue; expand_left = 0; expand_right = 0; for(int j = i+1; j < size && heights[j] >= heights[i]; ++j) ++expand_right; for(int j = i-1; j >= 0 && heights[j] >= heights[i]; --j) ++expand_left; curr_area = heights[i] * (expand_left + 1 + expand_right); if(curr_area > largest) largest = curr_area; curr_processed_num = heights[i]; } return largest; } };