最大子序和

1.题目

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例 1:

1
2
3
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。

示例 2:

1
2
输入:nums = [1]
输出:1

示例 3:

1
2
输入:nums = [0]
输出:0

2.分析

  • 使用动态规划,我们边遍历数组边算出当前的最大和,然后再比较之前的最大和得出最终的最大和

3.代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
//dp记录当前最大和
dp[0] = nums[0];
int ans = nums[0];
for (int i = 1; i < nums.length; i++) {
dp[i] = Math.max(dp[i-1]+nums[i],nums[i]);
if(dp[i]>ans){
ans = dp[i];
}
}
return ans;
}
}