int the first loop when i=0.
how we are able to access cumsum[i-1] while calculating the currentsum.
Accessing negative index
in this code cu_sum is my cumsum
#include using namespace std; int subarray(int a[],int cu_sum[],int n) { int sum{0}; for (int i=0;i<n;i++) { for(int j=i;j<n;j++) { int csum{0}; csum=cu_sum[j]-cu_sum[i-1]; if (sum<=csum) sum=csum; } } return sum; } int main() { int n{0}; cin>>n; int a[n],cu_sum[n]; cin>>a[0]; cu_sum[0]=a[0]; for(int i{1};i<n;i++) { cin>>a[i]; cu_sum[i]=cu_sum[i-1]+a[i]; } cout<<subarray(a,cu_sum,n); return 0; }
Hello @samardeep we are starting the loop from 1 and in the cumsum[0] we have already stored the a[0].
then cumsum[0] is not empty index.
it has some value.
Happy Learning!!
in first loop we are accessing cumsum [-1] ( when i=0 then i-1=-1).
Hello @samardeep yes you are right .
that is accesing the negative index and giving garbage values.
yes this is wrong.
this thing is done one of the lecture video …in array section and title of video is maximum subarray sum 2 of course interview preparation c++
if it is wrong then why it always show correct answer every time .when i cout cumsum [i-1]it shows 0 for whenever we access -ve index or index greater than its size .
in the code which i have shared is giving garbage value for that location.
it is changing every time on running the program.
but it is also giving the wrong answer for outputs.
how can you say that the output is coming out to be right?
wait i will ask the team to change this .