#41 Maximum Subarray

题目描述:

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;
    }
};


阅读更多
版权声明:三千微尘里,吾宁爱与憎 https://blog.csdn.net/haifischxia/article/details/52349410
个人分类: lintcode
上一篇#44 Minimum Subarray
下一篇#42 Maximum Subarray II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭