最大子数组
题目
给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。
注意事项
子数组最少包含一个数
样例
给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6
挑战
要求时间复杂度为O(n)
题解
贪心法,如果当前curMax或sum小于0则丢弃,否则更新sum。如数组全部由小于0的数组成,则直接返回最大值。
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(int[] nums) {
int sum = nums[0];
int curMax = nums[0];
int max = nums[0];
for (int i=1;i<nums.length;i++)
{
curMax = curMax < 0 ? nums[i] : (curMax + nums[i]);
sum = curMax > sum ? curMax : sum;
max = max < nums[i] ? nums[i] : max;
}
return sum < 0 ? max : sum;
}
}
Last Update 2016.8.26
本文介绍了一种在O(n)时间复杂度内找到整数数组中具有最大和的子数组的方法,并提供了一个Java实现示例。
348

被折叠的 条评论
为什么被折叠?



