In my program exception throwing index out of range -1, as for loop i index starts with 0 and on line 35 you are subtracting by 1
Maximum Subarray Sum2
int maxSubArray(vector& nums) { int maxSum = 0; int n = nums.size(); if(n == 1) return nums[0]; int cumSum[n]; cumSum[0] = nums[0]; for(int i=1; i<n; i++) { cumSum[i] = cumSum[i-1] + nums[i]; } for(int i=1; i<n; i++) { for(int j=i; j<n; j++) { maxSum = max(maxSum, cumSum[j]-cumSum[i-1]); } } return maxSum; }
@rahulwalkar89 we are assigning cumSum[0] a value before starting the loop, and we start the loop from i - 1. so we are never accessing the index -1, anywhere. In the future please save your code on ide.codingblocks.com and share the link instead of directly copy pasting the code.
Hi I am not talking about cumulative some loop other two nested loop where finding currentSum and masSum
@rahulwalkar89 in the nested loop also, i is starting from 1, and j is starting from i, so it cannot be negative.
Are you sure? i can see in video video i index starts from 0 and j = i
@rahulwalkar89 i was seeing the code that you have shared here, but yes, now I see sir had started the loop from i = 0. Yes, that would give an error so you’d have to use an if condition to check if i == 0 like here https://ide.codingblocks.com/s/213509
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.