//求子数组的最大和
public static int maxSubarray(int[] a, int size)
{
if (size <= 0) Console.WriteLine("error array size");
int sum = 0;
int max = 0;
int cur = 0;
while (cur < size)
{
sum += a[cur++];
if (sum > max)
{
max = sum;
}
else if (sum < 0)
{
sum = 0;
}
}
return max;
}
//求子数组的最大和
static int Max(int[] array, int size)
{
int curSum = 0;
int maxSum = 0;
for (int i = 0; i < size; i++)
{
curSum += array[i];
if (curSum < 0) curSum = 0;
if (curSum > maxSum) maxSum = curSum;
}
if (maxSum == 0)
{ //若是数组中的元素均为负数,则输出里面的最大元素
maxSum = array[0]; //当然这步也可以写到上面一个循环里
for (int i = 1; i < size; i++)
{
if (maxSum < array[i]) maxSum = array[i];
}
}
return maxSum;
}