Sword refers to offer 42. Maximum sum of consecutive sub-arrays
Title description
Problem-solving ideas
Note that this question is to find the maximum value of a continuous sub-array, and the idea is dp.
Why not the prefix sum?
Although the title description of the prefix sum is also a continuous sub-array , it must have the words "and is K" , pay attention to the distinction.
class Solution {
public int maxSubArray(int[] nums) {
//定义:dp[i]表示以nums[i]结尾的子数组和的最大值
int[] dp = new int[nums.length];
//base case
dp[0] = nums[0];
int res = nums[0];
for (int i = 1; i < nums.length; i++) {
dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
res = Math.max(res, dp[i]);
}
return res;
}
}