【LeetCode】53. Maximum Subarray


题目描述:

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.


思路:

用sum保存连续序列之和,用max表示最大值,一次遍历即可,时间复杂度O(n)。

  • sum<0,则舍弃前面的数
  • sum>max,则更新最大值max


代码实现:

int maxSubArray(int* nums, int numsSize) {
    int sum=0;
    int max=INT_MIN;
    for(int i=0;i<numsSize;i++){
        sum+=nums[i];
        if(sum>max){
            max = sum;
        }
        if(sum<0){
            sum = 0;
        }
    }
    return max;
}


 
comments powered by Disqus