leetcode 53 Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

最大字串的问题,该问题无论是各种面试题还是编程珠玑异或各种算法书中都是一道经典的题目。可惜每次都是草草地复制代码,没能深入理解其中的精髓,时间稍微久一点就会忘记。特记录如下:

O(n)算法

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int max = INT_MIN;
        int sum = 0;
        int i = 0;
        while(i < nums.size())
        {
            sum += nums[i];
            if(max < sum)
                max = sum;
            if(sum < 0)
                sum = 0;
            i++;
        }
        return max;
    }
};

猜你喜欢

转载自blog.csdn.net/happyjume/article/details/84369412