segmentation fault in array with given sum

Viewed 8

while writing code to find a subarray with given sum, if i try to initialize array with int , it works on my codeblocks but for large values if i try to initialize the array in long long,it shows segmentation fault. can someone explain me why it is showing the segfault. and if the code can be further optimized please tell me the way to do it. her's the code.

//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;


// } Driver Code Ends
class Solution
{
public:
    //Function to find a continuous sub-array which adds up to a given number.
    vector<int> subarraySum(int a[], int n, long long sum)
    {
        // Your code here
        int presum[n];
        presum[0]=a[0];
        int l=0,r=0;
        
        
        cout<<"presum ";
        for(int i=0; i<n; i++)cout<<presum[i]<<" ";
        cout<<endl;cout<<"arr ";
        for(int i=0; i<n; i++)cout<<a[i]<<" ";
        cout<<endl;
        for(int i=0; i<n; i++)
        {
            presum[i]=presum[i-1]+a[i];
            if(presum[i]==sum)
            {
                l=0;
                r=i;
                return {l+1,r+1};
            }
        }
        cout<<"presum ";
        for(int i=0; i<n; i++)
            cout<<presum[i]<<" ";
        cout<<endl;

        while(l<=r)
        {
            if(presum[r]-presum[l]==sum)
                return {l+2,r+1};
            else if((presum[r]-presum[l])>sum)
                l++;
            else
                r++;
        }
        return {-1};

    }
};

//{ Driver Code Starts.

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        long long s;
        cin>>n>>s;
        int arr[n];
        const int mx = 1e9;
        for(int i=0; i<n; i++)
        {
            cin>>arr[i];
        }
        Solution ob;
        vector<int>res;
        res = ob.subarraySum(arr, n, s);

        for(int i = 0; i<res.size(); i++)
            cout<<res[i]<<" ";
        cout<<endl;

    }
    return 0;
}
// } Driver Code Ends
0 Answers
Related