最优解法:Kadane 算法(一遍遍历)
核心思想
- 遍历数组时,维护当前最大和
- 如果前面的和是负数 ,只会拖累当前数,直接抛弃前面
- 否则,把当前数加进去
- 全程记录最大值
完整代码实现:
java
class Solution {
public int maxSubArray(int[] nums) {
if(nums==null || nums.length == 0){
return 0;
}
// 当前连续子数组的最大和
int currentMax = nums[0];
// 全局最大和(最终答案)
int globalMax = nums[0];
// 从第 2 个数开始遍历
for(int i = 1;i<nums.length;i++){
// 核心:
// 如果 currentMax 是负数 → 抛弃前面,从当前数重新开始
// 如果 currentMax 是正数 → 加上当前数,继续延长子数组
currentMax = Math.max(nums[i], currentMax + nums[i]);
// 更新全局最大值
globalMax = Math.max(globalMax, currentMax);
}
return globalMax;
}
}
最简单记忆口诀
前面是负的就扔掉,前面是正的就加上。 全程记录最大值。