The program is failing at the test case
4,-2,5,-2,2. The correct answer is 7 but it is giving 5. Why?
//maximum subarray_sum2
#include
using namespace std;
int main()
{
int n;
cout<<“Enter no of elements\n”;
cin>>n;
int arr[n],cumulative_sum[n],sum=0,maximum = INT_MIN,left,right;
cout<<“Enter “<<n<<” elements\n”;
for(int i=0;i<n;i++)
{
cin>>arr[i];
sum = sum + arr[i];
cumulative_sum[i] = sum;
}
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
sum = cumulative_sum[j] - cumulative_sum[i-1];
if(maximum < sum)
{
left = i;
right = j;
maximum = sum;
}
}
}
for(int i=left;i<=right;i++)
cout<<arr[i]<<' ';
cout<<endl;
cout<<"Maximum subarray sum is "<<maximum<<endl;
return 0;
}