When I provide a custom test case,it works fine. But when I submit,it shows run time error.
My code:
#include
using namespace std;
int main()
{
int t , n;
cin>>t;
for(int i = 0 ; i < t ; i++){
cin>>n;
int arr[1000];
for(int j = 0 ; j < n ; j++){
cin>>arr[j];
}
int currentSum = 0 , maxSum = 0;
for(int j = 0 ; j < n ; j++)
{
currentSum += arr[j];
if(currentSum < 0)
{
currentSum = 0;
}
maxSum = max(currentSum , maxSum);
}
cout<<maxSum<<endl;
}
return 0;
}
Maximum Subarray Sum using Kadan's algo
Instead of declaring the array as arr[1000], declare it as arr[n]
It worked with the solution. But what is the logic behind it?
According to the constraints the value of n can be above 1000. But you restricted the size of your array to 1000. So if n >1000, your code will give runtime error.
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.