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 maxSubSum = nums[0];
int dp[nums.size()];
if(nums.size() == 1) return nums[0];
for(int i = 0; i < nums.size(); ++i) {
dp[i] = nums[i];
}
for(int i = 1; i < nums.size(); ++i) {
dp[i] = max(dp[i], dp[i-1] + nums[i]);
}
for(int i = 0; i < nums.size(); ++i) {
maxSubSum = max(maxSubSum, dp[i]);
}
return maxSubSum;
}
};
注意maxSubSum要初始化成nums[0]而不是0。
优化的解法:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSubSum = nums[0];
int sum = maxSubSum;
if(nums.size() == 1) return nums[0];
for(int i = 1; i < nums.size(); ++i) {
sum = max(nums[i], sum + nums[i]);
if(maxSubSum < sum) maxSubSum = sum;
}
return maxSubSum;
}
};
因为此题不需要求出最大子段和区间,所以无需dp数组,一次遍历就可以求出。
最大连续子段和算法
491

被折叠的 条评论
为什么被折叠?



