(一)题目描述
给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。
(二)样例
样例1:
输入:
[−2,2,−3,4,−1,2,1,−5,3]
输出:
6
解释:
符合要求的子数组为[4,−1,2,1],其最大和为 6。
样例2:
输入:
[1,2,3,4]
输出:
10
解释:
符合要求的子数组为[1,2,3,4],其最大和为 10。
(三)注意事项
子数组最少包含一个数
(四)代码
public int maxSubArray(int[] nums) {
int len = nums.length;
if (len == 0) {
return 0;
}
int[] sum = new int[len];
sum[0] = nums[0];
for (int i = 1; i < len; i++) {
sum[i] = Math.max(nums[i], sum[i - 1] + nums[i]);//前 i 个最大和
}
int res = sum[0];
for (int i = 1; i < len; i++) {
res = Math.max(res,sum[i]);//sum[]数组存储最大的数组数和
}
return res;
}