Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example

Consideration
- We use a sum to represent the current sum. If adding current num can let sum larger than the previous one, we add this num to sum. Otherwise, we let sum equals to the current num.
- In each iteration, we compare the sum with the maximal result at the time. And update the maximal result if necessary.
== Solution ==
class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int sum = nums[0];
int max = sum;
for(int i = 1; i < nums.length; i++) {
sum += nums[i];
if(sum < nums[i])
sum = nums[i];
if(max<sum)
max = sum;
}
return max;
}
}
本文深入探讨了寻找具有最大和的连续子数组算法。通过迭代更新当前和最大值,实现高效求解。适用于整数数组,算法核心在于判断是否将当前元素加入到已有的子数组中,还是作为新的子数组的开始。
152

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



