给定一个int数组,求出连续子数组的最大和
思路:
动态规划
求的是连续子数组的最大和,就设f(i)为以i下标结尾的元素的连续子数组的最大和,f(i)只有2种情况,要么是nums[i]这一个数作为一段,要么就是f(i-1)+nums[i],因为要以i下标对应的元素结尾,所以比较得出较大值即可。
初始化就是f(0) =nums[0],因为连续子数组至少包含一个元素
class Solution {
public int maxSubArray(int[] nums) {
int res = Integer.MIN_VALUE;
int count=0;
for(int i=0;i<nums.length;i++){
count += nums[i];
if(count > res) res = count;
if(count < 0) count = 0;
}
return res;
}
}