【Leetcode】最大子数组和

 

 

采用分治算法,

数组区间[left, right], mid = (right + left) / 2

最大子数组存在于可能的三种情况:

[left, mid],  [mid + 1, right], 横跨前两个

而第三种情况可以拆成[lb, mid] 和 [mid + 1, ub]的并集

 

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        if (nums.size() == 1) return nums[0];
        if (nums.size() == 2) return max(nums[0], nums[1], nums[0] + nums[1]);

        int left = 0, right = nums.size() - 1, mid = left + (right - left) / 2;
        int left_max = nums[mid], right_max = 0, cur_left = 0, cur_right = 0;
        vector<int>left_nums, right_nums;
        for (int i = mid; i >= 0; --i)
        {
            cur_left += nums[i];
            if (cur_left > left_max) left_max = cur_left;
            left_nums.push_back(nums[i]);
        }
        if (mid + 1 <= right) right_max = nums[mid + 1];
        for (int i = mid + 1; i <= right; ++i)
        {
            cur_right += nums[i];
            if (cur_right > right_max) right_max = cur_right;
            right_nums.push_back(nums[i]);
        }
        return max(maxSubArray(left_nums), maxSubArray(right_nums), left_max + right_max);
    }

    int max(int a, int b, int c)
    {
        int m = a;
        if (m < b) m = b;
        if (m < c) m = c;
        return m; 
    }
};

 

posted @ 2022-04-12 21:52  鱼儿冒个泡  阅读(32)  评论(0编辑  收藏  举报