I am researching the maximum subarray problem. It would appear that I haven't gotten the core idea. Let's say you have the following array: int arr[] ={10, 4, 2, 12, 16, 1}
From what I understand the maximum subarray should be equal to 14, since the lowest and highest possible sub array is 2 (the third element) and 16 (the 5th element) right? Well, apperantly not. I implemented the linear time algorithm which I found here: http://heliang.me/wiki/index.php?title=4.1_The_maximum-subarray_problem
It's implementation in c++"
int max_sarr(int arr[], int size)
{
int max_sum = -9999;
int sum = 0;
for(int i = 0; i < size; i++)
{
sum += arr[i];
if(sum > max_sum)
max_sum = sum;
if(sum < 0)
sum = 0;
}
return sum;
}
int main()
{
int arr[] = {10, 4, 2, 12, 16, 1};
int p = max_sarr(arr, 6);
cout << p << endl;
return 0;
}
The output is 45. So... where is the mistake in my thought process ?