【数据结构入门

【数据结构入门,第1张

原题链接:53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

A subarray is a contiguous part of an array.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Example 2:

Input: nums = [1]
Output: 1

Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104

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.



方法一:贪心 思路:

遍历数组,记录当前和以及最大和,如果当前和大于最大和,就将最大和更新。



如果当前和小于0,那么就将当前和更新为0

c++代码:
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        // cur_sum当前和 max_sum最大和,初值给一个理论上的最小值
        int cur_sum = 0;
        int max_sum = INT_MIN;

        for(int i = 0; i < nums.size(); i ++ ){
            cur_sum += nums[i];
            if(cur_sum > max_sum)
                max_sum = cur_sum;
            if(cur_sum < 0)
                cur_sum = 0;
        }
        return max_sum;
    }
};
复杂度分析:
  • 时间复杂度:O(n)
  • 空间复杂度:O(1),只用了一个临时变量cur_sum


方法二:动态规划及改进 思路:

用一个数组dp[i]表示 以第 i 个数结尾的连续子数组的最大和。



比较dp[i-1]+nums[i]和nums[i]的最大值,并存为dp[i]
状态转移方程为max(dp[i] + nums[i], nums[i]),最后的答案为dp[n-1]

改进:

需要用一个数组来记录每一个dp[i],空间复杂度为O(n),但其实只要维护上一次的最大值,并将本次的最大值更新即可,空间复杂度可改进为O(1)

c++代码:
// 空间复杂度O(n)
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int n = nums.size();
        vector<int> dp(n);
        dp[0] = nums[0];
        int ans = nums[0];

        for(int i = 1; i < n; i ++ ){
            dp[i] = max(dp[i - 1] + nums[i], nums[i]);
            ans = max(ans, dp[i]);
        }
        return ans;
    }
};

// 改进 空间复杂度O(1)
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int n = nums.size();
        int pre = nums[0], ans = nums[0];

        for(int i = 1; i < n; i ++ ){
            pre = max(pre + nums[i], nums[i]);
            ans = max(ans, pre);
        }
        return ans;
    }
};
复杂度分析:
  • 时间复杂度:O(n)
  • 空间复杂度:不优化O(n), 优化O(1)


方法三:分治

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/567948.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存