Reputation: 21
I was solving this question. I wrote the code and received wrong answer for 10 test cases and correct for 6. I checked the constraints and since they are beyond the range of int therefore I replaced int by long long int. 9 test cases passed but the other 7 are showing segmentation fault now.
What can be the reason for this?
#include <iostream>
using namespace std;
int main()
{
long long int n,m;
cin>>n>>m;
long long int arr[n]={0};
long long int a,b,k;
long long int maxi=0;
while(m--)
{
cin>>a>>b>>k;
for(long long int i=a-1; i<b; i++)
{
arr[i]+=k;
}
}
for(long long int i=0; i<n; i++)
{
if(maxi<arr[i]){maxi=arr[i];}
}
cout<<maxi;
return 0;
}
Upvotes: 0
Views: 509
Reputation: 806
You can try with dynamic allocation
long long int *arr = new long long int[n];
don't forget to free up memory when you are done
delete []arr;
Upvotes: 0
Reputation: 2850
Main problem is
long long int arr[n]={0};
That's not valid standard C++, and if the array is too large, it won't fit on the stack, you need to dynamically allocate your array, preferably use std::vector
for it, like so
std::vector<long long int> arr{};
arr.resize(n);
Other then that, you should probably check if every array access is inside bounds.
Upvotes: 2