前面已经遇到了这一题目,就是简单的求给定数组的连续子序列的最大和。各元素必须直接相连。
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.
最容易想到的简单的循环方式为:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSum = nums[0];
for(int i = 0; i < nums.size(); i++)
{
int sum = 0;
for(int j = i; j < nums.size(); j++)
{
sum += nums[j];
if(sum > maxSum)
{
maxSum = sum;
}
}
}
return maxSum;
}
};
还有就是动态规划的做法,这里的就比较简单, dp[i]是以nums[i]为结尾的最大的子序列的和,递推方程为
dp[i] = max(dp[i - 1] + nums[i], nums[i] ) , 这很好理解,代码为:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSum = nums[0];
int dp[100000];
dp[0] = nums[0];
for(int i = 1; i < nums.size(); i++)
{
dp[i] = max(dp[i - 1] + nums[i], nums[i]);
if(maxSum < dp[i])
maxSum = dp[i];
}
return maxSum;
}
};