码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode[53]-Maximum Subarray

时间:2015-06-08 11:44:36      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:maximum   number   find   array   最大子序列   

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [?2,1,?3,4,?1,2,1,?5,4],
the contiguous subarray [4,?1,2,1] has the largest sum = 6.

More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

给定一个长度为n的序列,求其最大子序列和。
算法思路:使用动态规划求解,dp[i]表示在尾数在位置i上的最大子序列和,那么dp[i]可以表示为

  • dp[i] = max(dp[i-1] + nums[i],nums[i])
  • dp[0] = nums[0]

其中dp[0]表示初值。

代码如下:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {

        int n = nums.size();
        vector<int> dp(n);
        dp[0] = nums[0];
        int answer = dp[0];

        for(int i=1; i<n; ++i){
            dp[i] = max(dp[i-1]+nums[i],nums[i]);
            answer = max(answer,dp[i]);
        }

        return answer;

    }
};

leetcode[53]-Maximum Subarray

标签:maximum   number   find   array   最大子序列   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46408925

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!