Skip to content

Instantly share code, notes, and snippets.

@wfwei
Created May 27, 2013 11:46
Show Gist options
  • Select an option

  • Save wfwei/5656636 to your computer and use it in GitHub Desktop.

Select an option

Save wfwei/5656636 to your computer and use it in GitHub Desktop.
求连续子数组的最大和 题目详情: 一个整型数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和,求所有子数组的和的最大值,要求时间复杂度为O(n)。 例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,那么最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18, 请完成函数int MaxSum(int* a,int n)。 答题说明: 当全是负数的情况时,返回最大的那个负数
int MaxSum(int* a,int n)
{
int i=0, maxSum=1<<31, sum=0;
while(i<n){
sum += a[i++];
if(sum>maxSum)
maxSum = sum;
if(sum<0)
sum = 0;
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment