题目:
输入一个整形数组,数组里有正数,也有负数。数组中的一个或连续多个整数组成一个子数组。 求所有子数组的和的最大值。
/**
* 从0开始扫数组,max=0.
* 若累计的和为负数,则及时舍去,从下一位数开始为起点。
* 若累计的和不为负数,但所加的下一个数是负数,则要保存当前的连续子数组最大值
* @param nums
* @return
*/
public int Method1(int[] nums) {
if(nums == null || nums.length <= 0)
return 0;
/*
* 先用数组中的第一个数初始化一下max和temp
*/
int max = nums[0];
int temp = nums[0];
/*
* 从第二个数开始加
*/
for(int i = 1; i < nums.length; i++) {
if(temp < 0) {//如果之前的累加已经为负数了,给这个数自由吧 !让它本身作为起点
temp = nums[i];
}else {
temp = temp + nums[i];
}
//保存最大值
max = Math.max(temp, max);
}
return max;
}
/**
* 采用动态规划的办法
* @param nums
* @return
*/
public int Method2(int[] nums) {
if(nums == null || nums.length <= 0)
return 0;
int[] dp = new int[nums.length]; //用来记录以第i个结点为末尾的最大连续子数组
dp[0] = nums[0];
int max = nums[0];
for(int i = 1; i < nums.length; i++) {
if(dp[i -1] < 0) {
dp[i] = nums[i];
}else {
dp[i] = nums[i] + dp[i -1];
}
max = Math.max(max, dp[i]);
}
return max;
}