0

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;
    }

1 Answers1

0

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.

Abhinav Mathur
  • 7,791
  • 3
  • 10
  • 24
  • Yeah, you were right. It worked (with just a minor change). But almost every time I used the approach that I was using but it didn't cause me segmentation before on any online judge. Doesn't both mean the same? – Parminder Singh May 15 '22 at 03:16
  • @ParminderSingh refer to this: https://stackoverflow.com/questions/15013077/arrayn-vs-array10-initializing-array-with-variable-vs-numeric-literal#:~:text=If%20you%20want%20a%20%22variable,%3B%20when%20you're%20done! – Abhinav Mathur May 15 '22 at 04:15