Loading

【leetcode】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.

动态规划,用一个数组存储以当前数结尾最大的contiguous subarray,状态转移方程为:dp(n)=max(dp[n-1]+nums[n],nums[n])
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        // 动态规划 寻找递推公式 
        // dp(n) 以n结尾的数组最大连续subaarray 的累加和
        //dp(n)=max(dp[n-1]+nums[n],nums[n])
        int n=nums.size();
        vector<int>dp(n+1,0);
        int res=INT_MIN;
        for(int i=1;i<n+1;++i){
            dp[i]=max(dp[i-1]+nums[i-1],nums[i-1]);
            res=max(dp[i],res);
        }   
        return res;
    }
};

 

posted @ 2021-11-25 19:51  aalanwyr  阅读(21)  评论(0编辑  收藏  举报