Advertisement
maycod23

largest_rectangle_in_histogram

Jun 4th, 2022
1,062
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int largestRectangleArea(vector<int>& a)
  4.     {
  5.         //next smaller to left
  6.         //next smaller to right
  7.         int n=a.size();
  8.         stack<pair<int,int>> stk;
  9.         //what can i do while iterating over the stack from right keep track of the
  10.         //smaller element coming
  11.         int area=-1;
  12.         vector<int> width(n);
  13.         for(int i=(n-1);i>=0;i--)//from right to left fill in right vector
  14.             //next smaller element present in right
  15.         {
  16.            while(stk.size()>0&&stk.top().first>=a[i])
  17.            {
  18.                stk.pop();
  19.            }
  20.            if(stk.empty())
  21.            {
  22.                //nothing smaller to this in right
  23.               width[i]=(n-1);
  24.            }
  25.            else
  26.            {
  27.                width[i]=((stk.top().second)-1);
  28.                //ith element ke right[i] tak sare usse bade and barabar
  29.            }
  30.            stk.push(make_pair(a[i],i));
  31.         }
  32.         while(stk.size()>0) stk.pop();
  33.         for(int i=0;i<=(n-1);i++)//from left to right fill in left vector
  34.             //next smaller element present in left
  35.         {
  36.            while(stk.size()>0&&stk.top().first>=a[i])
  37.            {
  38.                stk.pop();
  39.            }
  40.            if(stk.empty())
  41.            {
  42.                //nothing smaller to this in left
  43.                int temp=0;
  44.               width[i]=(width[i]-temp+1);
  45.            }
  46.            else
  47.            {
  48.                int temp=((stk.top().second)+1);
  49.                width[i]=(width[i]-temp+1);
  50.                //ith element ke left[i] tak sare usse bade and barabar
  51.            }
  52.            stk.push(make_pair(a[i],i));
  53.         }
  54.         for(int i=0;i<=(n-1);i++)
  55.         {
  56.           area=max(area,(width[i]*a[i]));
  57.         }
  58.         return area;
  59.     }
  60. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement