题目:
分治法求解思路:
代码:
#include<iostream>
using namespace std;
int maxSum(int arr[], int left, int right)
{
int sum = 0;
if (left == right)
{
if (arr[left] > 0)
{
return arr[left];
}
else
{
return 0;
}
}
else
{
int center = (left + right) / 2;
int leftSum = maxSum(arr, left, center);
int rightSum = maxSum(arr, center + 1, right);
int s1 = 0;
int lefts = 0;
for (int i = center; i >= left; i--)
{
lefts += arr[i];
if (lefts > s1)
{
s1 = lefts;
}
}
int s2 = 0;
int rights = 0;
for (int i = center + 1; i <= right; i++)
{
rights += arr[i];
if (rights > s2)
{
s2 = rights;
}
}
int s = s1 + s2;
int maxx = max(leftSum, s);
sum = max(maxx, rightSum);
}
return sum;
}
int main()
{
int arr[] = { 1,5,-2,7,-3,77,-45,-77,100,45,-34,33 };
int len = sizeof(arr) / sizeof(int);
int maxsum = maxSum(arr, 0, len - 1);
cout << maxsum << endl;
}