[2018-11-25] [LeetCode-Week12] 53. Maximum Subarray 动态规划

https://leetcode.com/problems/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.

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.


d[i] = 以 i 结尾的最大子序列的值
d[i] = max(0, d[i-1]) + nums[i]
初始条件:d[0] = nums[0]


class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int d[100005];
        int n = nums.size();
        d[0] = nums[0];
        for (int i = 1; i < n; i++) {
            d[i] = max(0, d[i-1]) + nums[i];
        }
        
        int ans = d[0];
        for (int i = 1; i < n; i++) {
            ans = (ans > d[i]) ? ans : d[i];
        }
        return ans;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容