[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& 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;
    }
};

你可能感兴趣的:([2018-11-25] [LeetCode-Week12] 53. Maximum Subarray 动态规划)