1. 程式人生 > >leetcode 53 Maximum Subarray

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