先说下思路:利用分治的思想,对一个数组进行三种情况的划分,1.[low,mid]、2.[mid,high]和3.跨界子数组[low,high]
最大子数组必然出现在这三种情况之一。而第1、2种情况,又同样适用于最大子数组的递归情况,也就是说求第1、2种情况的递归思想和递归求一个数组的最大子数组的问题是一样的。
因此我们只要能实现求出最大跨界的子数组就找到了答案。
求跨界的最大子数组的思路就是:查看[i,mid]和[mid+1,i]的情况,分别求出这两种情况的最大值和边界,再对最大值求和,便找到了跨界最大子数组的和以及左右的边界值。
以下是求跨界的最大子数组的C语言实现:
int *findMaxCrossingSubarray(int arr[], int low, int mid, int high)
{
int *a = calloc(3, sizeof(int));
int leftSum = INT_MIN;
int leftMaxIndex = low;
int sum = 0;
for (int i = mid; i >= low; i--)
{
sum += arr[i];
if (sum > leftSum)
{
leftSum = sum;
leftMaxIndex = i;
}
}
int rightSum = INT_MIN;
int rightMaxIndex = high;
sum = 0;
for (int i = mid + 1; i <= high; i++)
{
sum += arr[i];
if (sum > rightSum)
{
rightSum = sum;
rightMaxIndex = i;
}
}
a[0] = leftMaxIndex;
a[1] = rightMaxIndex;
a[2] = leftSum + rightSum;
return a;
}
容易疏漏的地方:循环的时候,i的边界条件。
以下代码是完整的C语言递归实现:
//递归求解最大自数组的问题
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int *findMaxCrossingSubarray(int arr[], int low, int mid, int high); //寻找最大跨界子数组
int *findMaximumSubarray(int arr[], int low, int high); //递归寻找最大子数组
int main()
{
int arr[16] = {13, -3, -25, 1, -3, 16, 23, 18, -20, -7, -12, -50, -22, 15, -4, 7};
int *result = findMaximumSubarray(arr, 0, 15);
printf("左边界为%d", result[0]);
printf("右边界为%d", result[1]);
printf("最大跨界子数组的和为%d", result[2]);
free(result);
return 0;
}
//返回最大自数组的左右边界和最大子数组的和
int *findMaxCrossingSubarray(int arr[], int low, int mid, int high)
{
int *a = calloc(3, sizeof(int));
int leftSum = INT_MIN;
int leftMaxIndex = low;
int sum = 0;
for (int i = mid; i >= low; i--)
{
sum += arr[i];
if (sum > leftSum)
{
leftSum = sum;
leftMaxIndex = i;
}
}
int rightSum = INT_MIN;
int rightMaxIndex = high;
sum = 0;
for (int i = mid + 1; i <= high; i++)
{
sum += arr[i];
if (sum > rightSum)
{
rightSum = sum;
rightMaxIndex = i;
}
}
a[0] = leftMaxIndex;
a[1] = rightMaxIndex;
a[2] = leftSum + rightSum;
return a;
}
int *findMaximumSubarray(int arr[], int low, int high)
{
int *a = calloc(3, sizeof(int));
if (high == low)
{
a[0] = low;
a[1] = high;
a[2] = arr[low];
return a;
}
int mid = (low + high) / 2;
int *leftResult = findMaximumSubarray(arr, low, mid);
int *rightResult = findMaximumSubarray(arr, mid + 1, high);
int *midResult = findMaxCrossingSubarray(arr, low, mid, high);
if (leftResult[2] >= midResult[2] && leftResult[2] >= rightResult[2])
{
free(rightResult);
free(midResult);
return leftResult;
}
else if (rightResult[2] >= midResult[2] && rightResult[2] >= leftResult[2])
{
free(leftResult);
free(midResult);
return rightResult;
}
else
{
free(leftResult);
free(rightResult);
return midResult;
}
}
复杂度为O(nlgn),完毕。