Advertisement
urmisaha

Area under histogram

Oct 25th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define maxm 1000001
  3. #define ll long long
  4. using namespace std;
  5.  
  6. ll T, N, x, max_area, area;
  7. stack<ll> st;
  8. vector<ll> hist(maxm);
  9.  
  10. int main()
  11. {
  12.     ios_base::sync_with_stdio(false);
  13.     cin>>T;
  14.     while(T--){
  15.         cin>>N;
  16.         max_area = 0;
  17.         for(ll i=0; i<N; ++i)
  18.             cin>>hist[i];
  19.         for(ll i=0; i<N; ++i){
  20.             if(st.empty() || hist[st.top()] <= hist[i])
  21.                 st.push(i);
  22.             else{
  23.                 while(!st.empty() && hist[st.top()] > hist[i]){
  24.                     x = hist[st.top()];
  25.                     st.pop();
  26.                     area = st.empty() ? (x * i) : (x * (i-1-st.top()));
  27.                     max_area = max(max_area, area);
  28.                 }
  29.                 st.push(i);
  30.             }
  31.         }
  32.         while(!st.empty()){
  33.             x = hist[st.top()];
  34.             st.pop();
  35.             area = st.empty() ? (x * N) : (x * (N-1-st.top()));
  36.             max_area = max(max_area, area);
  37.         }
  38.         cout<<max_area<<endl;
  39.     }
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement