一、题目
给你一个整数数组 nums
,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
子数组 是数组中的一个连续部分。
输入:nums = [-2,1,-3,4,-1,2,1,-5,4] 输出:6 解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
二、思路
1 确定状态
opt[i]表示以i为结尾的子数组中,最大连续子数组和,opt[0] = -2 ,opt[1] = 1
2 状态转移方程
opt[i] = max(nums[i],opt[i-1] + nums[i])
3 边界条件
opt[0] = nums[0]
4 顺序和结果
正序赋值opt数组,结果是opt数组中的最大值
三、代码
class Solution {
public int maxSubArray(int[] nums) {
int[] opt = new int[nums.length];
opt[0] = nums[0];
int max = nums[0];
for (int i = 1;i<nums.length;i++){
opt[i] = Math.max(nums[i],opt[i-1] + nums[i]);
if (opt[i] > max) max = opt[i];
}
return max;
}
}