index
title: 最大子序和 date: 2019-08-21T11:00:41+08:00 draft: false categories: leetcode
题目
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:解题思路
public int maxSubArray(int[] nums) {
if (nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int[] res = new int[nums.length];
res[0] = nums[0];
int max = res[0];
for (int i = 1; i < nums.length; i++) {
int curMax = nums[i] + res[i - 1];
if (curMax > nums[i]) {
res[i] = curMax;
} else {
res[i] = nums[i];
}
max = Math.max(max, res[i]);
}
return max;
}Last updated