Facebook
From Prateek Mishra, 3 Years ago, written in C++.
Embed
Download Paste or View Raw
Hits: 476
  1. int Solution::largestRectangleArea(vector<int> &height) {
  2.     int n=height.size();
  3.     stack<int>s;
  4.     int value=0;
  5.     s.push(0);
  6.     for(int i=1; i<n; i++){
  7.        
  8.         if(s.empty()  || height[i]>=height[s.top()]){
  9.             s.push(i);
  10.         }
  11.         else {
  12.             while(!s.empty()  and height[s.top()]>height[i]){
  13.                 int val=height[s.top()];
  14.                 s.pop();
  15.                 int area;
  16.                 if(s.empty()){
  17.                     area=val*i;
  18.                     value=max(value,area);
  19.                 }
  20.                 else{
  21.                     area=val*(i-s.top()-1);
  22.                     value=max(value,area);
  23.                 }
  24.             }
  25.             s.push(i);
  26.         }
  27.     }
  28.    
  29.     while(!s.empty()){
  30.         int val=height[s.top()];
  31.         s.pop();
  32.         int area;
  33.         if(s.empty()){
  34.                     area=val*n;
  35.                     value=max(value,area);
  36.         }
  37.         else{
  38.             area=val*(n-s.top()-1);
  39.             value=max(value,area);
  40.         }
  41.  
  42.     }
  43.     return value;
  44. }
  45.