一、Description:
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
.
二、Ideas:
这道题的目的是求最大子串和,可以通过动态规划的方法实现O(n)的时间复杂度。首先定义一个最大值变量max,设为无穷小,再定义一个中间值变量mid,设为0,然后从数组第一个数开始遍历,每个位置的最大值为:Max(mid+num[i],num[i])。
三、Code:
class Solution {
public int maxSubArray(int[] nums) {
int max=java.lang.Integer.MIN_VALUE;
int mid=0;
for(int i=0;i<nums.length;i++){
if(mid+nums[i]>=nums[i]){
mid+=nums[i];
if(mid>max) max=mid;
}
else {
mid=nums[i];
if(mid>max) max=mid;
}
}
return max;
}
}