1. 最大子数组和,返回最大和
public int maxSubArray(ArrayList<Integer> nums) {
// -1 is not proper for illegal input
if (nums == null || nums.isEmpty()) return -1;
int sum = 0, minSum = 0, maxSub = Integer.MIN_VALUE;
for (int num : nums) {
minSum = Math.min(minSum, sum);
sum += num;
maxSub = Math.max(maxSub, sum - minSum);
}
return maxSub;
}
2. maximum subarray ||,返回满足最大的子数组和的子数组。
这里是求不相重叠的两个子数组和的和最大值,做过买卖股票系列的题的话这道题就非常容易了,既然我们已经求出了单一子数组的最大
Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.
Note
The subarray should contain at least one number
Example
思路和股票买卖III一样:
For given [1, 3, -1, 2, -1, 2], the two subarrays are [1, 3] and [2, -1, 2] or [1, 3, -1, 2] and [2], they both have the largest sum 7.
分层两段,左边和右边分别计算max subarray,然后两边加起来最大的就是结果。
这道题目里没有明确说一定要两段(比如一段可不可以,比如左边没有值,右边有一段),但是实际结果是一段是不可以的。。。
- public int maxTwoSubArrays(ArrayList<Integer> nums) {
- int[] left = new int[nums.size()];
- int localMax = 0;
- int globalMax = Integer.MIN_VALUE;
- for (int i = 0; i < nums.size(); i++) {
- localMax = Math.max(nums.get(i), localMax + nums.get(i));
- globalMax = Math.max(localMax, globalMax);
- left[i] = globalMax;
- }
- localMax = 0;
- globalMax = Integer.MIN_VALUE;
- int result = Integer.MIN_VALUE;
- for (int i = nums.size()-1; i >= 0; i--) {
- if (i < nums.size()-1) {
- result = Math.max(result, left[i] + globalMax);
- }
- localMax = Math.max(nums.get(i), localMax + nums.get(i));
- globalMax = Math.max(localMax, globalMax);
- }
- return result;
- }