# leetcode-53-Maximum Subarray

### Maximum Subarray

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.

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n=nums.size();
int s=0;
int max_=nums[0];
for(int i=0;i<n;i++){
s+=nums[i];
if(max_<s) max_=s; // 如果大于最大值 就更新最大值
if(s<0) s=0;              // s<0  就从下一个数开始 重新记数
}
return max_;
}
};

DP  参考 七月算法-动态规划

dp[i]是以nums[i]结尾的最大子数组的和，

dp[i]=max(dp[i-1]+nums[i],nums[i])

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
int dp[n];// dp[i]是 以nums[i]结尾的最大子数组的和
dp[0]=nums[0];
int max_=nums[0];
for(int i = 1;i < n;i++){
dp[i] = max(dp[i-1]+nums[i],nums[i]);
max_ = max(dp[i],max_);
}
return max_;
}
};

class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
int cur=nums[0];
int max_=nums[0];
for(int i = 1;i < n;i++){
cur = max(cur+nums[i],nums[i]);
max_ = max(cur,max_);
}
return max_;
}
};

int max(int a,int b){
return a>b?a:b;
}

int merge(int* nums,int s,int t){
if(s == t) return nums[t];
int mid = (s + t) >> 1;
int max_ = max(merge(nums,s,mid),merge(nums,mid + 1,t)); // s..mid 与 mid + 1..t的最大和
int leftmax = nums[mid],rightmax = nums[mid + 1],cur;             // 即左右部分的最大和
cur = leftmax;
for(int i = mid - 1;i >= s;i--){ // 以mid结尾的 最大和
cur += nums[i];
leftmax = max(cur,leftmax);
}
cur = rightmax;
for(int i = mid + 2;i <= t;i++){ // 以mid+1开始的 最大和
cur += nums[i];
rightmax = max(cur,rightmax);
}
return max(max_,leftmax + rightmax); // 返回最大和
}

int maxSubArray(int* nums, int numsSize) {
return merge(nums,0,numsSize-1);
}


#### maximum-subarray Java 贪心

2016-09-03 14:27:38

#### leetcode ：Find the contiguous subarray within an array (containing at least one number) which has th

2014-09-28 10:23:31

#### 最大子数组问题 Maximum Subarray

2016-05-02 15:41:44

#### LWC 55：713. Subarray Product Less Than K

2017-10-23 14:53:08

#### Leetcode121.+Leetcode53. Kadane算法解决最大子数组问题

2017-10-14 15:19:31

#### 最大子数组递归和非递归(暴力)

2014-04-12 14:23:56

#### SPOJ NUMTRYE Number Theory (Easy) （pollard_rho分解质因数）

2015-09-23 19:29:25

#### member access within misaligned address 0x000000000031 for type 'struct ListNode', which requires 8

2017-01-23 00:15:24

#### 【LeetCode-面试算法经典-Java实现】【053-Maximum Subarray（最大子数组和）】

2015-07-29 06:46:34

#### 算法之美——求子串最大和

2012-11-01 21:32:30