Getting segmentation fault

#include<iostream>
#include<climits>
using namespace std;
int main(){
    int n;
    cin>>n;
    int max_left=INT_MIN;
    int a[1000000]={0};
    int left[1000000]={0};
    for (int i = 0; i < n; i++)
    {
        cin>>a[i];
        max_left=max(max_left,a[i]);
        left[i]=max_left;
    }
    int right[1000000]={0};
    max_left=INT_MIN;
   for (int i = n-1; i >=0; i--)
   {  max_left=max(max_left,a[i]);
      right[i]=max_left;
   }
   int water=0;
   for (int i = 0; i < n; i++)
   {
       int mini=min(left[i],right[i]);
       water=water+(a[i]-mini);
   }
   cout<<water;

    return 0;
}

You cannot build an integer array of size >10^5 in the main. This will give a segmentation fault.
If you want the array size to be upto 10^7 then you can declare it as global outside the main.

STILL THE CODE IS NOT WORKING PLEASE CORRECT IT AND EXPLAIN THE PROBLEM

#include<iostream>
#include<climits>
using namespace std;
int a[1000000];
int right[1000000];
int left[1000000];
int main(){
    int n;
    cin>>n;
    int max_left=INT_MIN;
    for (int i = 0; i < n; i++)
    {
        cin>>a[i];
       
    }
    for (int i = 0; i < n; i++)
    {
         max_left=max(max_left,a[i]);
        left[i]=max_left;
    }
    
 
    max_left=INT_MIN;
   for (int i = n-1; i >=0; i--)
   {  max_left=max(max_left,a[i]);
      right[i]=max_left;
   }
   int water=0;
   for (int i = 0; i < n; i++)
   {
       int mini=min(left[i],right[i]);
       water=water+(a[i]-mini);
   }
   cout<<water;

    return 0;
}

I just changed the variable name.gloabal variable name as left and right may be reserved so it was not working. Your code is now running. But it is not giving the expected o/p. Check that.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.