spider68

Maximum Rectangular Area in a Histogram

Jun 17th, 2020
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4.  
  5. int main() {
  6.     int i,j,t,n;
  7.     cin>>t;
  8.     while(t--)
  9.     {
  10.         cin>>n;
  11.         long long a[n];
  12.         for(i=0;i<n;i++)cin>>a[i];
  13.         stack<int>s;
  14.         long long sm,maxx=0;
  15.         i=0;
  16.         while(i<n)
  17.         {
  18.             if(s.empty()||a[s.top()]<=a[i])s.push(i++);
  19.             else{
  20.                 j=s.top();
  21.                 s.pop();
  22.                 sm=a[j]*(s.empty()?i:i-s.top()-1);
  23.                 maxx=maxx>sm?maxx:sm;
  24.             }
  25.         }
  26.         while(!s.empty())
  27.         {
  28.             j=s.top();
  29.             s.pop();
  30.             sm=a[j]*(s.empty()?i:i-s.top()-1);
  31.             maxx=maxx>sm?maxx:sm;
  32.         }
  33.         cout<<maxx<<endl;
  34.     }
  35.     return 0;
  36. }
Add Comment
Please, Sign In to add comment