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.
晕死,被这题搞晕了。dp[i]数组表示以i为序列终端的最大值。然后扫描即可。
与PAT甲级1007. Maximum Subsequence Sum (25)类似
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int len=nums.size(),i;
if(!len){
return 0;
}
int dp[len];
dp[0]=nums[0];
for(i=1;i<len;i++){
dp[i]=max(nums[i],dp[i-1]+nums[i]);
}
int maxn=dp[0];
for(i=1;i<len;i++){
if(dp[i]>maxn){
maxn=dp[i];
}
}
return maxn;
}
};
其实我还是不能理解其他大佬的思路:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int len=nums.size(),i,ans,tmp;
if(!len){
return 0;
}
ans=tmp=nums[0];
for(i=1;i<len;i++){
if(tmp>0){
tmp=tmp+nums[i];
}
else{
tmp=nums[i];
}
ans=max(ans,tmp);
}
return ans;
}
};
参考MOOC浙大数据结构
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int len=nums.size(),i;
if(!len){
return 0;
}
int maxsum=nums[0],nowsum=0;
for(i=0;i<len;i++){
nowsum=nowsum+nums[i];
if(nowsum>maxsum){
maxsum=nowsum;
}
if(nowsum<0){
nowsum=0;
}
}
return maxsum;
}
};