最大子序列和

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例:

输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int low = 0;
        int high = nums.size() - 1;
        return divid(nums, low, high);
    }

    int divid(std::vector<int>& a, int low,int high) {
        int s1 = 0, s2 = 0, s3 = 0;
        if (low == high) {
            return a[low];
        }
        else{
            int mid = (low + high) / 2;
            s1 = divid(a, low, mid);
            s2 = divid(a, mid + 1, high);
            s3 = crossingSubArray(a, low, mid, high);
            int s = (s1 > s2) ? s1 : s2;
            return s3 > s ? s3 : s;
        }
    }
    int crossingSubArray(std::vector<int>& a, int low, int mid, int high) {
        int Sleft = a[mid];
        int Sright = a[mid + 1];
        int sumLeft = 0, sumRight = 0;
        for (int i = mid; i >= low; i--) {
            sumLeft += a[i];
            Sleft = (Sleft > sumLeft) ? Sleft : sumLeft;
        }
        for (int j = mid+1; j <= high; j++) {
            sumRight += a[j];
            Sright = (Sright > sumRight) ? Sright : sumRight;
        }
        return Sleft + Sright;
    }
};

你可能也喜欢

发表评论

电子邮件地址不会被公开。