Advertisement
srijan44

histogramarea(stack)

Apr 3rd, 2020
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4.  
  5. int area(int *arr,int n){
  6.  
  7.     stack<int> s;
  8.  
  9.     int top;
  10.     int mx=INT_MIN;
  11.     int area;
  12.  
  13.     int i=0;
  14.     while(i<n){
  15.  
  16.         if(s.empty() || arr[s.top()] < arr[i]){
  17.             s.push(i);
  18.             i++;
  19.         }
  20.         else{
  21.             top=s.top();
  22.             s.pop();
  23.  
  24.             if(s.empty()) area = arr[top]*i;
  25.            
  26.             else area = arr[top]*(i-s.top()-1);
  27.  
  28.             mx=max(area,mx);
  29.  
  30.         }
  31.     }
  32.  
  33.     while(!s.empty()){
  34.         top=s.top();
  35.         s.pop();
  36.  
  37.         if(s.empty()) area = arr[top]*i;
  38.  
  39.         else{
  40.             area = arr[top]*(i-s.top()-1);
  41.         }
  42.  
  43.         mx=max(mx,area);
  44.  
  45.     }
  46.  
  47.     return mx;
  48.  
  49. }
  50.  
  51. int32_t main() {
  52.  
  53.     #ifndef ONLINE_JUDGE
  54.     // for getting input from input.txt
  55.     freopen("input.txt", "r", stdin);
  56.     // for writing output to output.txt
  57.     freopen("output.txt", "w", stdout);
  58.     #endif
  59.  
  60.     int n;
  61.     cin >> n;
  62.  
  63.     int arr[n];
  64.    
  65.     for(int i=0;i<n;i++){
  66.         cin >> arr[i];
  67.     }
  68.  
  69.     cout << area(arr,n) << endl;
  70.  
  71.  
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement