4.1.3—栈—Largest Rectangle in Histogram

来源:互联网 发布:男神的偶像知乎 编辑:程序博客网 时间:2024/06/01 23:11
描述
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.

#include<iostream>#include<string>#include<vector>#include<stack>using namespace std;int my_max(int s1, int s2){if (s1>s2)return s1;elsereturn s2;}int largestRectangleArea(vector<int> &height){stack<int> s;height.push_back(0);int result = 0;for (int i = 0; i < height.size();){if (s.empty() || height[i] > height[s.top()])s.push(i++);else{int tmp = s.top();s.pop();result = my_max(result, height[tmp] * (s.empty() ? i : i - s.top() - 1));}}return result;}int main(){vector<int> input;input.push_back(2);input.push_back(3);input.push_back(4);input.push_back(5);input.push_back(6);input.push_back(7);int res = largestRectangleArea(input);cout << res << endl;}

原创粉丝点击