Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 53. Maximum Subarray #53

Open
grandyang opened this issue May 30, 2019 · 0 comments
Open

[LeetCode] 53. Maximum Subarray #53

grandyang opened this issue May 30, 2019 · 0 comments

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019


请点击下方图片观看讲解视频
Click below image to watch YouTube Video
Video

Given an integer array nums, find the subarray with the largest sum, and return its sum.

Example 1:

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

Example 2:

Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

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.

这道题让求最大子数组之和,并且要用两种方法来解,分别是 O(n) 的解法,还有用分治法 Divide and Conquer Approach,这个解法的时间复杂度是 O(nlgn),那就先来看 O(n) 的解法,这个方法叫做卡达内算法 Kadane's Algorithm,卡卡和齐达内的合体?可以参见维基百科上的这个帖子,定义两个变量 res 和 curSum,其中 res 保存最终要返回的结果,即最大的子数组之和,curSum 初始值为0,每遍历一个数字 num,比较 curSum + num 和 num 中的较大值存入 curSum,然后再把 res 和 curSum 中的较大值存入 res,以此类推直到遍历完整个数组,可得到最大子数组的值存在 res 中,代码如下:

C++ 解法一:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int res = INT_MIN, curSum = 0;
        for (int num : nums) {
            curSum = max(curSum + num, num);
            res = max(res, curSum);
        }
        return res;
    }
};

Java 解法一:

public class Solution {
    public int maxSubArray(int[] nums) {
        int res = Integer.MIN_VALUE, curSum = 0;
        for (int num : nums) {
            curSum = Math.max(curSum + num, num);
            res = Math.max(res, curSum);
        }
        return res;
    }
}

题目还要求我们用分治法 Divide and Conquer Approach 来解,这个分治法的思想就类似于二分搜索法,需要把数组一分为二,分别找出左边和右边的最大子数组之和,然后还要从中间开始向左右分别扫描,求出的最大值分别和左右两边得出的最大值相比较取最大的那一个,代码如下:

C++ 解法二:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        if (nums.empty()) return 0;
        return dfs(nums, 0, (int)nums.size() - 1);
    }
    int dfs(vector<int>& nums, int left, int right) {
        if (left >= right) return nums[left];
        int mid = left + (right - left) / 2, leftSum = 0, rightSum = 0;
        for (int i = mid - 1, curSum = 0; i >= left; --i) {
            curSum += nums[i];
            leftSum = max(leftSum, curSum);
        }
        for (int i = mid + 1, curSum = 0; i <= right; ++i) {
            curSum += nums[i];
            rightSum = max(rightSum, curSum);
        }
        return max({dfs(nums, left, mid - 1), dfs(nums, mid + 1, right), leftSum + nums[mid] + rightSum});
    }
};

Java 解法二:

public class Solution {
    public int maxSubArray(int[] nums) {
        if (nums.length == 0) return 0;
        return dfs(nums, 0, nums.length - 1);
    }
    public int dfs(int[] nums, int left, int right) {
        if (left >= right) return nums[left];
        int mid = left + (right - left) / 2, leftSum = 0, rightSum = 0;
        for (int i = mid - 1, curSum = 0; i >= left; --i) {
            curSum += nums[i];
            leftSum = Math.max(leftSum, curSum);
        }
        for (int i = mid + 1, curSum = 0; i <= right; ++i) {
            curSum += nums[i];
            rightSum = Math.max(rightSum, curSum);
        }
        return Math.max(Math.max(dfs(nums, left, mid - 1), dfs(nums, mid + 1, right)), leftSum + nums[mid] + rightSum);
    }
}

Github 同步地址:

#53

类似题目:

Best Time to Buy and Sell Stock

Maximum Product Subarray

Degree of an Array

Longest Turbulent Subarray

Maximum Absolute Sum of Any Subarray

Maximum Subarray Sum After One Operation

Maximum Score Of Spliced Array

Substring With Largest Variance

Count Subarrays With Score Less Than K

Maximum Value of a String in an Array

Find the Substring With Maximum Cost

K Items With the Maximum Sum

参考资料:

https://leetcode.com/problems/maximum-subarray/

https://leetcode.com/problems/maximum-subarray/discuss/20211/Accepted-O(n)-solution-in-java

https://leetcode.com/problems/maximum-subarray/discuss/20193/DP-solution-and-some-thoughts

https://leetcode.com/problems/maximum-subarray/discuss/20200/Share-my-solutions-both-greedy-and-divide-and-conquer

LeetCode All in One 题目讲解汇总(持续更新中...)

(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~)

知识星球 喜欢请点赞,疼爱请打赏❤️~.~

微信打赏

|

Venmo 打赏


---|---

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant