Leetcode 53. 最大子序和

m:序列中最大的值【当序列都小于0的时候返回它】
M:包含k位置连续子序(如果大于0)的最大值或0【当包含k位置的最大值小于0时,不取k位置的数】

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int ans = 0, M = 0, m = nums[0];
        for (auto &x : nums)
            ans = max(M = max(0, M + x), ans), m = max(m, x);
        return ans == 0 ? m : ans;
    }
};

猜你喜欢

转载自blog.csdn.net/bendaai/article/details/80189890