class Solution {
public int maxSubArray(int[] nums) {
if(nums==null || nums.length==0){
return 0;
}
int sum=-101;
int temp=0;
for(int i:nums){
temp= i+temp;
if(sum<temp){
sum=temp;
}
if(temp<0){
temp=0;
}
}
return sum;
}
}
思路:使用贪心的思想,如果前面的某个序列计算出的和为负数,那么就让temp归零。
sum记录当前最大的子数组的和。

该博客介绍了一种解决最大子数组和问题的贪心策略。通过遍历数组,不断累加元素并更新最大子数组和,当累加和变为负数时将其重置为0。这种方法简洁高效,能找出数组中连续子数组的最大和。
436

被折叠的 条评论
为什么被折叠?



