您的位置:首页 > 其它

leetcode 53. Maximum Subarray

2017-04-06 14:44 483 查看

53. Maximum Subarray  c语言实现

Description

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array
[-2,1,-3,4,-1,2,1,-5,4]
,

the contiguous subarray
[4,-1,2,1]
has the largest sum =
6
.

int maxSubArray(int* nums, int numsSize) {
int i,j;
int max,temp;
if(numsSize == 0) return 0;
if(numsSize == 1) return nums[0];
max = nums[0];
for(i = 0; i < numsSize - 1; i++)
{
j=i + 1;
if(nums[i] > max) max = nums[i];//单个值比max大
temp = nums[i];
while(j < numsSize)
{
temp += nums[j];
if(temp > max){
max = temp;
}
j++;
}
}
if(nums[i] > max) max = nums[i];//比较最后一个元素
return max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息