给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例 1:
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
示例 2:
输入:nums = [1]
输出:1
示例 3:
输入:nums = [0]
输出:0
示例 4:
输入:nums = [-1]
输出:-1
示例 5:
输入:nums = [-100000]
输出:-100000
提示:
1 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105
动态规划:
解法1:
class Solution {
public int maxSubArray(int[] nums) {
// [-2,1,-3,4,-1,2,1,-5,4]
//[4,-1,2,1]
//实际上加的是 1-》4
// 2->4+1=5(-1与2相遇 pre=1)
//3->5+1=6 (pre=1,max=1)
int num = 0, maxNums = nums[0];
for (int x : nums) {
num = Math.max(num + x, x);//比较数组两个数字判断那个是最大的
maxNums = Math.max(maxNums, num);//比较当前的最大值和前面最大值
}
return maxNums;
}
}
解法2:
class Solution {
public int maxSubArray(int[] num) {
int[] nums = new int[num.length];
nums[0] = num[0];
int max = nums[0];
for (int i = 1; i < num.length; i++) {
nums[i] = Math.max(nums[i - 1], 0) + num[i];
max = Math.max(max, nums[i]);
}
return max;
}
}