题目描述:
输入一个 非空 整型数组,数组里的数可能为正,也可能为负。 数组中一个或连续的多个整数组成一个子数组。 求所有子数组的和的最大值。 要求时间复杂度为O(n)。
样例:
输入:[1, -2, 3, 10, -4, 7, 2, -5]
输出:18
动态规划问题:
class Solution {
public int maxSubArray(int[] nums) {
int sum = nums[0],max = nums[0];
for(int i = 1;i<nums.length;i++){
sum+=nums[i];
if(sum<nums[i]) sum = nums[i];
if(sum>max) max = sum;
}
return max;
}
}