码迷,mamicode.com
首页 > 编程语言 > 详细

lincode.41 最大子数组

时间:2017-09-05 23:11:55      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:nap   alert   group   script   snap   foo   tiny   www.   code   

最大子数组

 

给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

注意事项

子数组最少包含一个数

样例

给出数组[?2,2,?3,4,?1,2,1,?5,3],符合要求的子数组为[4,?1,2,1],其最大和为6

挑战

要求时间复杂度为O(n)

标签
 
 
class Solution {
public:
    /*
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    int maxSubArray(vector<int> &nums) {
        // write your code here
        int s=nums.size();
        int res=nums[0];
        int cn=0;
        for(int i =0;i<s;i++){
            cn+=nums[i];
            if(res<cn)
                res=cn;
            if(cn<0)
                cn=0;
        }
        return res;
    }
};

  

lincode.41 最大子数组

标签:nap   alert   group   script   snap   foo   tiny   www.   code   

原文地址:http://www.cnblogs.com/ygtzds/p/7482177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!