原题链接:力扣
我们用 f(i)代表以第 i个数结尾的「连续子数组的最大和」,那么很显然我们要求的答案就是:
因此我们只需要求出每个位置的f(i),采用动态规划的原理我们可以知道f(i)=max(f(i-1)+nums[i],nums[i])
class Solution {
public int maxSubArray(int[] nums) {
int pre = 0, maxAns = nums[0];
for (int x : nums) {
pre = Math.max(pre + x, x);
maxAns = Math.max(maxAns, pre);
}
return maxAns;
}
}