Largest Rectangle in Histogram

来源:互联网 发布:零基础学qt4编程pdf 编辑:程序博客网 时间:2024/06/07 18:42

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.

For example,
Given heights = [2,1,5,6,2,3],
return 10.

solution 1:

class Solution {public:    int largestRectangleArea(vector<int>& heights);};int Solution::largestRectangleArea(vector<int>&  heights){    int heightsSize = heights.size();  std::stack<int> s;int i = 0;int max = 0;while(i < heightsSize){if(s.empty() || heights[s.top()] <= heights[i]){s.push(i);i++;} else {int index = s.top();s.pop();int tmp_max = heights[index] *(s.empty() ? i : (i - s.top() - 1));if(max < tmp_max){max = tmp_max;}}}while(!s.empty()){int index = s.top();s.pop();int tmp_max = heights[index] *(s.empty() ? i : (i - s.top() - 1));if (max < tmp_max){max = tmp_max;}}return max;}

https://leetcode.com/problems/largest-rectangle-in-histogram/

http://www.geeksforgeeks.org/largest-rectangle-under-histogram/
0 0
原创粉丝点击