Problem: Maximum Rectangular Area in a Histogram
link: https://practice.geeksforgeeks.org/problems/maximum-rectangular-area-in-a-histogram-1587115620/1
Website: GeeksForGeeks
I am getting a Segmentation Fault in the below code of C++. Could anyone tell me the reason behind this and what should I need to change? Trying to figure it out since yesterday. Although the same type of code was given A.C. on leetcode.
long long getMaxArea(long long arr[], int n)
{
// Your code here
long long left[n], right[n];
stack<int> st, st2;
for (int i = 0; i < n; i++) {
while (st.size() and arr[i] <= arr[st.top()]) st.pop();
if (st.size()) left[i] = st.top();
else left[i] = -1;
st.push(i);
}
for (int i = n-1; i >= 0; i--)
{
while (st2.size() and arr[i] <= arr[st2.top()]) st2.pop();
if (st2.size()) right[i] = st2.top();
else right[i] = n;
st2.push(i);
}
long long max_area = 0;
for (int i = 0; i < n; i++) {
long long area = arr[i] * (right[i] - left[i] - 1);
max_area = max(max_area, area);
}
return max_area;
}
Instead of
long long left[n], right[n];
Try using
long long *left = new int[n], *right = new int[n];
Incorrectly allocating memory might be the reason behind the crash.