LeetCode 0053. Maximum Subarray【DP,最大子序和】

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.

思路1

  1. 使用贪心的方法,每一步选择最佳方案,最后得到全局最优
  2. 在每个步骤中更新
    1. 当前元素
    2. 当前元素位置的最大和
    3. 迄今为止的最大和

时间复杂度 O ( N ) O(N) 空间复杂度 O ( 1 ) O(1)

在这里插入图片描述

代码1

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int max_sum = nums[0], cur_sum = nums[0];
        for(int i = 1; i < nums.size(); i++)
        {
            cur_sum = max(cur_sum + nums[i], nums[i]); // 当前最大和
            max_sum = max(max_sum, cur_sum);  // 历史最大和
        }
        return max_sum;
    }
};

思路2

首先对数组进行遍历,当前最大连续子序列和为 sum,结果为 max_sum
如果 sum > 0,则说明 sum 对结果有增益效果,则 sum 保留并加上当前遍历数字。如果 sum <= 0,则说明 sum 对结果无增益效果,需要舍弃,则 sum 直接更新为当前遍历数字。每次比较 summax_sum 的大小,将最大值置为 max_sum,遍历结束返回结果。实际处理过程中可以使用滚动数组来存储值。

时间复杂度 O ( N ) O(N) 空间复杂度 O ( 1 ) O(1)

代码2

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int len = nums.size(), max_sum = nums[0];
        for(int i = 1; i < len; i++)
        {
            if(nums[i-1] > 0)
                nums[i] += nums[i-1] ;
            max_sum = max(max_sum, nums[i]);
        }
        return max_sum;
    }
};
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int ans = nums[0], sum = 0;
        for(const auto &it : nums)
        {
            if(sum > 0)
                sum += it;
            else
                sum = it;
            ans = max(sum, ans);
        }
        return ans;
    }
};

在线处理

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int res =-0x7fffffff, temp = 0;
        for(int i = 0; i < nums.size(); i++)
        {
            temp += nums[i];
            if(temp > res)  res = temp;
            if(temp < 0)  temp = 0;
        }
        return res;
    }
};

思路3

分治法

代码3


发布了166 篇原创文章 · 获赞 27 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/HdUIprince/article/details/105690805