1.穷举法
class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int max = Integer.MIN_VALUE;
for (int begin = 0; begin < nums.length; begin++){
for (int end = begin; end < nums.length; end++){
int sum = 0;
for (int i = begin; i <= end; i++){
sum += nums[i];
}
max = Math.max(max, sum);
}
}
return max;
}
}
都2021年了,Java使用这个方法最后几个测试用例提交会超出时间限制。
2.对暴力穷举法的优化:从begin加到end的sum,下一次计算sum的时候可以直接用上次计算过的sum加上nums[end]即可.
class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int max = Integer.MIN_VALUE;
for (int begin = 0; begin < nums.length; begin++){
int sum = 0;
for (int end = begin; end < nums.length; end++){
sum += nums[end];
max = Math.max(max, sum);
}
}
return max;
}
}
3.分治法
class Solution {
public int maxSubArray(int[] nums){
return maxSubArray(nums, 0, nums.length);
}
public int maxSubArray(int[] nums, int begin, int end) {
if (end - begin < 2) return nums[begin];
int mid = (begin + end) >> 1;
int leftMax = Integer.MIN_VALUE;
int leftSum = 0;
//中间两个for循环是结果子序列被mid分隔
for (int i = mid - 1; i >= begin; i--){
leftSum += nums[i];
leftMax = Math.max(leftMax, leftSum);
}
int rightMax = Integer.MIN_VALUE;
int rightSum = 0;
for (int i = mid; i < end; i++){
rightSum += nums[i];
rightMax = Math.max(rightMax, rightSum);
}
return Math.max(leftMax + rightMax, Math.max(
maxSubArray(nums, begin, mid),//最大的子序列在左边的情况
maxSubArray(nums, mid, end) //最大的子序列在右边的情况
));
}
}