给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
思路:动态规划的思想,申请一个同样长度的数组res[]做状态记录。res[i]表示以nums[i]结尾的连续子数组的最大和的值,它等于res[i - 1] + nums[i] 和 nums[i]中的较大值。
public int maxSubArray(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int[] res = new int[nums.length];
res[0] = nums[0];
int max = res[0];
for (int i = 1; i < nums.length; i++) {
res[i] = (nums[i] + res[i - 1] > nums[i])? nums[i] + res[i - 1]: nums[i];
if(res[i] > max)
max = res[i];
}
return max;
}
本文介绍了一种使用动态规划方法解决寻找具有最大和的连续子数组的问题。通过一个示例,[-2,1,-3,4,-1,2,1,-5,4],展示了如何计算出最大子数组和为6的过程。
1671

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



