有下面的函数,返回一个整数数组中 “最大子数组的和” ,max2 为何返回不对呢?
//返回一个数组中最大的子数组的和。
# include <iostream>
# include <stdio.h>
# include <string.h>
int MaxSum(int* arr, int size)
{
int current = 0; //current max sum
int max = current;
for (int i = 0; i < size; i++)
{
if (current < 0)
current = 0;
current += arr[i];
if (current > max)
max = current;
}
return max;
}
int main(void)
{
char x[40], y[40];
int a1[5] = { -1, 5, 6, -7, 3 };
int a2[5] = { -5, -4, -8, -1, -10 };
int a3[5] = { -1, 5, 6, -7, 10 };
int max1, max2, max3;
max1 = MaxSum(a1, 5);
max2 = MaxSum(a2, 5); //这个应该返回 -1, 但是返回 0.
max3 = MaxSum(a3, 5);
}