There is an error in this code explained in the video.
Under the for loop, in the statement ( line 35 ) :
currentSum=cumSum[j]-cum[i-1];
in first iteration i=0, so cumSum[-1] is coming which contains garbage value.
Error in maximum subarray sum code
Hi poorva send the full code
#include
using namespace std;
int main(){
int a[1000];
int n;
int left=-1, right=-1;
int cur_sum=0, max_sum=0;
cout<<"Enter number of elements : "<<endl;
cin>>n;
cout<<endl;
int c_sum[n]={0};
cout<<"Enter elements : "<<endl;
cin>>a[0];
c_sum[0]=a[0];
for(int i=1;i<n;i++){
cin>>a[i];
c_sum[i]=a[i]+c_sum[i-1];
}
cout<<endl;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
cur_sum=c_sum[j]-c_sum[i-1];
if(cur_sum>max_sum){
max_sum=cur_sum;
left = i;
right=j;
}
}
}
cout<<"Maximum sum is : "<<max_sum<<endl;
cout<<"Sub - array is : "<<endl;
for(int k=left;k<=right;k++){
cout<<a[k]<<" ";
}
return 0;
}
If I==0
Cursum=csum[j]
Only
Means we have to make a if-else condition for this.
absolutely…
u got it