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.
这个题有很多种解法:
最先想到的是暴力解法,时间复杂度是O(n2)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max_val = INT_MIN;
for (int begin = 0; begin < nums.size(); begin ++) {
int val = nums[begin];
max_val = max(max_val, val);
for (int end = begin + 1; end < nums.size(); end ++) {
val += nums[end];
max_val = max(max_val,val);
}
}
return max_val;
}
};
一维动态规划
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if(nums.size()==0) return 0;
vector<int> dp(nums.size(),0);
int res=nums[0];
for(int i=0;i<nums.size();i++){
if(i==0) dp[0]=nums[0];
dp[i]=max(dp[i-1]+nums[i],nums[i]);
if(dp[i]>res) res=dp[i];
}
return res;
}
};
一维滚动动态规划:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.size() == 0) return 0;
int res = nums[0];
int curent = nums[0];
for (int i = 1; i < nums.size(); i++) {
curent = curent > 0 ? curent + nums[i] : nums[i];
res = max(res, curent);
}
return res;
}
};
分治: