关闭

#41 Maximum Subarray

标签: lintcodedynamic programming
112人阅读 评论(0) 收藏 举报
分类:

题目描述:

Given an array of integers, find a contiguous subarray which has the largest sum.

 Notice

The subarray should contain at least one number.

Example

Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

Challenge 

Can you do it in time complexity O(n)?

题目思路:

这题和#44一毛一样,就不多说了。

Mycode(AC = 28ms):

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
        if (nums.size() == 0) return 0;
        
        int local = nums[0], global = nums[0];
        for (int i = 1; i < nums.size(); i++) {
            local = max(local + nums[i], nums[i]);
            global = max(global, local);
        }
        
        return global;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14895次
    • 积分:2257
    • 等级:
    • 排名:第17346名
    • 原创:221篇
    • 转载:1篇
    • 译文:0篇
    • 评论:10条
    文章分类
    文章存档