Negative index in array

in “maximum subarray sum 2” code, in the nested loop part, for the first iteration, we are using the value for cumSum[0-1] and the code is working fine. but its a garbage value. please tell me why we are doing this then. is the value at -1 index always zero??

my ide program number 62954.

Hi Raghav, No, the value at -1 index is not always zero. For some compilers it may be zero, for others it may be a garbage value. Thus, it is not advisable to access the value at -1 index. The code here is working fine because we’re finding the maximum sum and we’re subtracting the value of cummsum[-1] from cummsum[j]. This value is coming out to be negative for garbage values like 0, 21938 etc. and thus is not being used while calculating the final answer. You can check how the code is working by printing the values of newsum for every iteration.
It is advisable to start the loop for i=1, so that we do not access values at negative indices.