在C ++中使用分而治之算法的最大子数组总和
假设我们有一个带有正值和负值的数据列表。我们必须找到其总和最大的连续子数组的总和。假设列表包含{-2,-5,6,-2,-3,1,5,-6},则最大子数组的总和为7。它是{6,-2,-3的总和,1,5}
我们将使用分而治之方法解决此问题。步骤如下所示-
步骤 -
将数组分为两部分
查找以下三个中的最大值
左子数组的最大子数组总和
右子数组的最大子数组总和
最大子数组总和,以使子数组越过中点
示例
#include <iostream> using namespace std; int max(int a, int b) { return (a > b)? a : b; } int max(int a, int b, int c) { return max(max(a, b), c); } int getMaxCrossingSum(int arr[], int l, int m, int h) { int sum = 0; int left = INT_MIN; for (int i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left) left = sum; } sum = 0; int right = INT_MIN; for (int i = m+1; i <= h; i++) { sum = sum + arr[i]; if (sum > right) right = sum; } return left + right; } int maxSubArraySum(int arr[], int low, int high) { if (low == high) return arr[low]; int mid = (low + high)/2; return max(maxSubArraySum(arr, low, mid), maxSubArraySum(arr, mid+1, high), getMaxCrossingSum(arr, low, mid, high)); } int main() { int arr[] = {-2, -5, 6, -2, -3, 1, 5, -6}; int n = sizeof(arr)/sizeof(arr[0]); int max_sum = maxSubArraySum(arr, 0, n-1); printf("Maximum contiguous sum is %d", max_sum); }
输出结果
Valid String