给定一个整数数组:(-2,1,-3,4,-1,2,1,-5,4)用分治法找出总和最大的连续数列,写出核心函数并返回总和。c++
时间: 2023-10-02 07:05:32 浏览: 164
C++ 让函数返回数组的方法
这道题可以使用分治法来解决,将数组分成左半部分、右半部分和跨越中心的部分三个部分。其中,左半部分和右半部分可以分别递归求解,而跨越中心的部分则需要从中心向两边扩展来求解。
下面是核心函数的实现:
```c++
int maxSubArraySum(int arr[], int left, int right) {
if (left == right) {
return arr[left];
}
int mid = (left + right) / 2;
int leftMaxSum = maxSubArraySum(arr, left, mid);
int rightMaxSum = maxSubArraySum(arr, mid + 1, right);
int leftCrossSum = INT_MIN, rightCrossSum = INT_MIN;
int sum = 0;
for (int i = mid; i >= left; i--) {
sum += arr[i];
if (sum > leftCrossSum) {
leftCrossSum = sum;
}
}
sum = 0;
for (int i = mid + 1; i <= right; i++) {
sum += arr[i];
if (sum > rightCrossSum) {
rightCrossSum = sum;
}
}
int crossSum = leftCrossSum + rightCrossSum;
return max(max(leftMaxSum, rightMaxSum), crossSum);
}
```
其中,`arr`为输入的整数数组,`left`和`right`为数组的左右边界。函数返回数组中的最大连续子序列和。
完整的代码如下:
```c++
#include <iostream>
#include <climits>
using namespace std;
int maxSubArraySum(int arr[], int left, int right) {
if (left == right) {
return arr[left];
}
int mid = (left + right) / 2;
int leftMaxSum = maxSubArraySum(arr, left, mid);
int rightMaxSum = maxSubArraySum(arr, mid + 1, right);
int leftCrossSum = INT_MIN, rightCrossSum = INT_MIN;
int sum = 0;
for (int i = mid; i >= left; i--) {
sum += arr[i];
if (sum > leftCrossSum) {
leftCrossSum = sum;
}
}
sum = 0;
for (int i = mid + 1; i <= right; i++) {
sum += arr[i];
if (sum > rightCrossSum) {
rightCrossSum = sum;
}
}
int crossSum = leftCrossSum + rightCrossSum;
return max(max(leftMaxSum, rightMaxSum), crossSum);
}
int main() {
int arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int maxSum = maxSubArraySum(arr, 0, n - 1);
cout << "Max subarray sum is " << maxSum << endl;
return 0;
}
```
阅读全文