标签: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[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;
}
};
标签:maximum number find array 最大子序列
原文地址:http://blog.csdn.net/dream_angel_z/article/details/46408925