给定一个有n(n≥1)个整数的序列,要求求出其中最大连续子序列的和。(分治策略求解, Java or Python) 例如: 序列(-2,11,-4,13,-5,-2)的最大子序列和为20 序列(-6,2,4,-7,5,3,2,-1,6,-9,10,-2)的最大子序列和为16。 规定一个序列最大连续子序列和至少是0,如果小于0,其结果为0。
时间: 2023-12-17 11:03:27 浏览: 91
Python语言描述最大连续子序列和
好的,这是一个经典的问题。下面是Java代码实现:
```
public class MaxSubArray {
public static int maxSubArray(int[] nums) {
return maxSubArrayHelper(nums, 0, nums.length - 1);
}
private static int maxSubArrayHelper(int[] nums, int left, int right) {
if (left == right) {
return Math.max(0, nums[left]);
}
int mid = (left + right) / 2;
int leftMax = maxSubArrayHelper(nums, left, mid);
int rightMax = maxSubArrayHelper(nums, mid + 1, right);
int crossMax = maxCrossingSubArray(nums, left, mid, right);
return Math.max(Math.max(leftMax, rightMax), crossMax);
}
private static int maxCrossingSubArray(int[] nums, int left, int mid, int right) {
int leftSum = Integer.MIN_VALUE;
int sum = 0;
for (int i = mid; i >= left; i--) {
sum += nums[i];
leftSum = Math.max(leftSum, sum);
}
int rightSum = Integer.MIN_VALUE;
sum = 0;
for (int i = mid + 1; i <= right; i++) {
sum += nums[i];
rightSum = Math.max(rightSum, sum);
}
return Math.max(leftSum, 0) + Math.max(rightSum, 0);
}
public static void main(String[] args) {
int[] nums1 = new int[]{-2, 11, -4, 13, -5, -2};
int[] nums2 = new int[]{-6, 2, 4, -7, 5, 3, 2, -1, 6, -9, 10, -2};
System.out.println(maxSubArray(nums1)); // 输出20
System.out.println(maxSubArray(nums2)); // 输出16
}
}
```
这个算法的时间复杂度是O(nlogn),其中n是序列的长度。
阅读全文