Maximum Subarray
LeetCode.53. Maximum Subarray Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Example:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
给你一个整数数组
nums
,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。子数组 是数组中的一个连续部分。
提示:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
First Solution
假设sum<=0,那么后面的子序列不包含目前的子序列,所以令sum = num[i];
如果sum > 0对于后面的子序列是有好处的。
res = Math.max(res, sum)保证可以找到最大的子序和。
public int maxSubArray(int[] nums) {
int sum = 0;
int res = nums[0];
for (int i = 0; i < nums.length; i++) {
if (sum > 0) {
sum += nums[i];
}else {
sum = nums[i];
}
res = Math.max(res, sum);
}
return res;
}
该算法更为简便之处是忽略了对子序列的寻找比较,而是根据规律直接找出最佳答案.
对于含有正数的序列而言,最大子序列肯定是正数,所以头尾肯定都是正数.我们可以从第一个正数开始算起,每往后加一个数便更新一次和的最大值;当当前和成为负数时,则表明此前序列无法为后面提供最大子序列和,因此必须重新确定序列首项.