Maximum Sum Subarray part 2

why this code is not giving error in line 26 when i = 0
this is the code in the video of maximum sum subarray part two
and it runs fine on coding blocks ide
but it gives wrong output in code blocks

#include<bits/stdc++.h>
using namespace std;

int main()
{
int n;
cin >> n;

int maximum_sum = 0, current_sum = 0;
int start , endindex = -1;
int a[n];
cin >> a[0];
int cumSum[n];
cumSum[0] = a[0];

for(int i =1; i<n; i++)
{
    cin >> a[i];
    cumSum[i] = cumSum[i-1] + a[i];
}

for(int i = 0; i<n; i++)
{
    for(int j = i; j<n; j++)
    {
        current_sum = cumSum[j] - cumSum[i-1];
        if(current_sum > maximum_sum)
        {
            maximum_sum = current_sum;
            start = i;
            endindex = j;
        }
    }
}

cout << "maximum sum is " << maximum_sum << endl;
for(int i = start; i<=endindex; i++)
    cout << a[i] << " ";

return 0;

}

Hey, cumSum[-1] stores the garbage value or in online judge this value is NULL.
Tht’s why it is giving error, So, you can define it like -> cumSum[-1]=0;
Now, it will work fine.

1 Like

Updated Code-> https://ide.codingblocks.com/s/74423

1 Like

Can I access any negative index in an array on online judge? Like arr[-105] or is it only limited to just -1

1 Like

in online judge, it always give 0 value.

1 Like