题目:给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
例:输入: [-2,1,-3,4,-1,2,1,-5,4],输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
我的答案:
1)暴力法(太慢了,不推荐)
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length;
if(n == 1) return nums[0];
int max = nums[0];
int sum = 0;
for(int i = 0; i < n-1; i++){
if(nums[i] < 0 && nums[i] < nums[i+1])
continue;
max = Math.max(max,nums[i]);
sum = nums[i];
for(int j = i+1; j < n; j++){
sum = sum + nums[j];
if(sum > max)
max = sum;
}
}
max = Math.max(max,nums[n-1]);
return max;
}
}
讨论区好的方法:
1.贪心算法
每一步都选择最佳方案,到最后就是全局最优的方案。
如果该元素和前面的元素相加没有使自己变大,则抛弃前面的元素
该算法通用且简单:遍历数组并在每个步骤中更新:
当前元素、当前元素位置的最大和、迄今为止的最大和
public int maxSubArray(int[] nums) {
int localMax = nums[0], globalMax = nums[0];
for(int i = 1; i < nums.length; i++) {
localMax = Math.max(nums[i] + localMax, nums[i]);
globalMax = Math.max(localMax, globalMax);
}
return globalMax;
}
时间复杂度:O(N)。只遍历一次数组。
空间复杂度:O(1)。只使用了常数空间。
2.动态规划
沿数组移动并在原数组修改。
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length, maxSum = nums[0];
for(int i = 1; i < n; ++i) {
if (nums[i - 1] > 0) nums[i] += nums[i - 1];
maxSum = Math.max(nums[i], maxSum);
}
return maxSum;
}
}
时间复杂度:O(N)。只遍历一次数组。
空间复杂度:O(1)。只使用了常数空间。