特判一下全负数
接着每当出现一段数总和为负数,就全部丢弃
每当出现一段数总和为正数,并且增加的是正数,更新答案
与标程的动态规划以及分治有异曲同工之妙
class Solution {
public int maxSubArray(int[] nums) {
int ans = 0;
int now = 0;
boolean flag = true;
for (int num : nums) {
if (num >= 0) {
flag = false;
break;
}
}
if (flag == true) {
int maxNum = nums[0];
for (int num : nums) {
if (num > maxNum) {
maxNum = num;
}
}
return maxNum;
}
for (int i = 0; i < nums.length; i++) {
if (now + nums[i] > 0) {
now += nums[i];
if (nums[i] > 0) {
ans = Math.max(ans, now);
}
} else {
now = 0;
}
}
return ans;
}
}
2021/8/22 动归重写
// 冲刺011
class Solution {
public int maxSubArray(int[] nums) {
int ans = nums[0];
int now = nums[0];
int len = nums.length;
for (int i = 1; i < len; i++) {
now = Math.max(now + nums[i], nums[i]);
ans = Math.max(now, ans);
}
return ans;
}
}