来自力扣的53. 最大子数组和
题目描述是这样的:
给你一个整数数组 nums
,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。子数组 是数组中的一个连续部分。
测试用例如下: 输入:nums = [-2,1,-3,4,-1,2,1,-5,4] 输出:6 解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
以下是两个方向的解题
思路是这样的,举例第一种;bj从前向后的增加,同时加上对应位置数组上的数
前提是bj不小于0,否则从后面重新从0开始。
从前向后
class Solution {
public int maxSubArray(int[] nums)
{int n = nums.length;
int bj=0;int bmax=nums[0];
for(int i=0;i<n;i++)
{ if (bj<0)
bj=0;
bj+=nums[i];
bmax=Math.max(bj,bmax);
}
return bmax;
}
}
从后向前
class Solution {
public int maxSubArray(int[] nums)
{int n = nums.length;
int aj=0;int amax=nums[0];
for(int i=n-1;i>=0;i--)
{ if (aj<0)
aj=0;
aj+=nums[i];
amax=Math.max(aj,amax);
}
return amax;
}
}