-
Notifications
You must be signed in to change notification settings - Fork 1
/
311.cpp
81 lines (73 loc) · 1.81 KB
/
311.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to find largest rectangular area possible in a given histogram.
long long getMaxArea(long long arr[], int n)
{
vector<int> l(n,-1),r(n,n);
stack<int> s;
for(int i=0;i<n;i++){
if(s.empty()){
s.push(i);
continue;
}
else if(arr[i]>arr[s.top()]){
l[i]=s.top();
s.push(i);
}
else{
while(!s.empty() && arr[i]<=arr[s.top()]){
s.pop();
}
if(!s.empty()) l[i]=s.top();
s.push(i);
}
}
while(!s.empty()) s.pop();
for(int i=n-1;i>=0;i--){
if(s.empty()){
s.push(i);
continue;
}
else if(arr[i]>arr[s.top()]){
r[i]=s.top();
s.push(i);
}
else{
while(!s.empty() && arr[i]<=arr[s.top()]){
s.pop();
}
if(!s.empty()) r[i]=s.top();
s.push(i);
}
}
long long int ans=INT_MIN;
for(int i=0;i<n;i++){
long long int k=(r[i]-l[i]-1)*arr[i];
if(ans<k) ans=k;
}
return ans;
}
};
// { Driver Code Starts.
int main()
{
long long t;
cin>>t;
while(t--)
{
int n;
cin>>n;
long long arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
Solution ob;
cout<<ob.getMaxArea(arr, n)<<endl;
}
return 0;
}
// } Driver Code Ends