【LeetCode053】Maximum Subarray

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int len = nums.size();
        int *end_here = new int[len];  // 右边返回的是指针
        end_here[0] = nums[0]; //end_here用来记录终止在此处的子数列的最大值
        int max_sum = nums[0];
        for(int i = 1; i < len; ++i){
            end_here[i] = nums[i] + (end_here[i-1] > 0 ? end_here[i-1] : 0);  //替代if,else语句
            max_sum = max(max_sum, end_here[i]); //
        }
        return max_sum;
    }
};

Youtube上面有个详细的讲解,针对三种时间复杂度的解法,有时间再回头仔细看

三种解答方法GitHub

猜你喜欢

转载自blog.csdn.net/weixin_39458342/article/details/87632144