给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
答案:
class Solution {
public int maxSubArray(int[] nums) {
int maxSum = Integer.MIN_VALUE;
int curSum = 0;
for (int num : nums) {
curSum = Math.max(curSum + num, num);
maxSum = Math.max(maxSum, curSum);
}
return maxSum;
}
}
本文介绍了一种高效算法,用于解决在整数数组中寻找具有最大和的连续子数组问题。通过实例演示了如何实现这一算法,并给出了具体的代码示例。
366

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



