###### LeetCode 53. 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.

##### 先计算每一点的total sum，再用最大的sum - minsum
public int maxSubArray(int[] nums) {
int min = 0, sum = 0, max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum - min > max) {
max = sum - min;
}
if (sum < min) {
min = sum;
}
}
return max;
}
##### 归纳法来解，假设每个位置i,都包含i，取一个最大值，那么每个位置的最大值可能为i本身，或者是i之前的包括i-1的最大值，max(nums[i], g(i-1)).
    public int maxSubArray(int[] nums) {
int max = Integer.MIN_VALUE, sum = -1;
for (int i = 0; i < nums.length; i++) {
sum = sum > 0 ? nums[i]  + sum : nums[i];
max = Math.max(max, sum);
}
return max;
}
//这是可以返回subarray的index的版本。
public int[] maxSubArray(int[] nums) {
int min = 0, sum = 0, max = Integer.MIN_VALUE, sindex = 0, eindex = 0, minindex = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (sum - min > max) {
max = sum - min;
sindex = minindex;
eindex = i;
}
if (sum < min) {
min = sum;
minindex = i;
}
}
int[] result = {max, sindex + 1, eindex};
return result;
}


#### LeetCode(53)Maximum Subarray

2014-01-29 11:00:36

#### LeetCode53. Maximum Subarray 动态规划和分治法

2016-09-20 23:26:36

#### 【leetcode】【53】Maximum Subarray

2016-03-01 11:21:30

#### LeetCode第53之 Maximum Subarray（两种方法）

2016-06-27 20:48:11

#### LeetCode-53-Maximum Subarray(DP/分治)-Medium

2016-01-16 21:07:20

#### leetcode解题之53 # Maximum Subarray Java版

2017-03-12 21:45:30

#### LeetCode 53. Maximum Subarray Java

2016-08-11 10:07:42

#### [LeetCode]53.Maximum Subarray

2015-01-27 20:23:55

#### [leetcode]53. Maximum Subarray 最大连续子串python实现【medium】

2016-06-15 00:30:28

#### 53. Maximum Subarray-动态规划/分治

2016-09-04 17:30:45

## 不良信息举报

LeetCode 53. Maximum Subarray