Largest Rectangle in Histogram LeetCode solution in C++
1class Solution {2private:3vector<int> nextSmallerElement(vector<int> &arr, int n) {4stack<int> s;5s.push(-1);6vector<int> ans(n);78for (int i = n - 1; i >= 0; i--) {9int curr = arr[i];1011while (s.top() != -1 && arr[s.top()] >= curr) {12s.pop();13}14ans[i] = s.top();15s.push(i);16}17return ans;18}19vector<int> prevSmallerElement(vector<int> &arr, int n) {20stack<int> s;21s.push(-1);22vector<int> ans(n);2324for (int i = 0; i < n; i++) {25int curr = arr[i];2627while (s.top() != -1 && arr[s.top()] >= curr) {28s.pop();29}30ans[i] = s.top();31s.push(i);32}33return ans;34}3536public:37int largestRectangleArea(vector<int> &heights) {38int n = heights.size();39int area = 1, ans = INT_MIN;4041vector<int> next(n);42next = nextSmallerElement(heights, n);4344vector<int> prev(n);45prev = prevSmallerElement(heights, n);4647for (int i = 0; i < n; i++) {48int l = heights[i];4950if (next[i] == -1) {51next[i] = n;52}53int b = next[i] - prev[i] - 1;5455area = l * b;56ans = max(ans, area);57}58return ans;59}60};