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.
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.

中文:给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。


分析:将求n个数组的最大子段和,转换为分别求出以第1个,第2个,…,第i个,…,第n个数组结尾的最大字段和,再找出这n个结果里面最大的,即为结果。
动态规划算法:
第i个状态(dp[i])即为以第i个数字结尾的最大子段和。由于以第i-1个数字结尾的最大子段和(dp[i-1])与nums[i]相邻。
状态转移方程:
dp[i]=dp[i-1]+nums[i] (dp[i-1]>0)
边界值: dp[0]=num[0]

图示:

代码:

class Solution {
public:
    int maxSubArray(vector& nums) {
        int n=nums.size();
        vector dp(n,0);
        dp[0]=nums[0];
        int res=dp[0]; //放答案
        for(int i=1;i

你可能感兴趣的:(LeetCode,动态规划)