# 最大子序列和问题之算法优化

xiao小栗子
2个月前 阅读 9 点赞 1

int maxSubsequenceSum(const int a[], int n)
{
int i, j, k;
int thisSum, maxSum = 0;
for (i = 0; i < n; i++)
for (j = i; j < n; j++)
{
thisSum = 0;
for (k = i; k < j; k++)
thisSum += a[k];
if (thisSum > maxSum)
maxSum = thisSum;
}
return maxSum;
}


int maxSubsequenceSum(const int a[], int n)
{
int i, j;
int thisSum, maxSum = 0;
for (i = 0; i < n; i++)
{
thisSum = 0;
for (j = i; j < n; j++)
{
thisSum += a[j];
if (thisSum > maxSum)
maxSum = thisSum;
}
}
return maxSum;
}


### 算法三：分治（divide-and-conquer）策略

#### 分治策略：

int maxSubsequenceSum(const int a[], int left, int right)
{
int i, mid, maxLeftSum, maxRightSum;
int maxLeftBorderSum, leftBorderSum;
int maxRightBorderSum, rightBorderSum;
if (left == right) {      /*基准情况*/
if (a[left] >= 0)
return a[left];
else
return 0;
}
mid = left + (right - left) / 2;
maxLeftSum = maxSubsequenceSum(a, left, mid);   /*左半部分的最大和*/  maxRightSum = maxSubsequenceSum(a, mid+1, right); /*右半部分的最大和*/
/*下面求穿过中点的最大和*/
maxLeftBorderSum = 0, leftBorderSum = 0;
for (i = mid; i >= left; i--)
/*中点及其以左的最大和*/
{
leftBorderSum += a[i];
if (leftBorderSum > maxLeftBorderSum)
maxLeftBorderSum = leftBorderSum;
}
maxRightBorderSum = 0, rightBorderSum = 0;
for (i = mid+1; i <= right; i++) /*中点以右的最大和*/
{
rightBorderSum += a[i];
if (rightBorderSum > maxRightBorderSum)
maxRightBorderSum = rightBorderSum;
}
/*返回三部分中的最大值*/
return max3(maxLeftSum, maxRightSum, maxLeftBorderSum+maxRightBorderSum);
}

int max3(int a, int b, int c)
{
int maxNum = a;
if (b > maxNum)
maxNum = b;
if (c > maxNum)
maxNum = c;
return maxNum;
}


T(1) = 1

T(n) = 2T(n/2) + O(n)

### 算法四：

int maxSubsequenceSum(const int a[], int n)
{
int i;
int maxSum, thisSum;
maxSum = thisSum = 0;
for (i = 0; i < n; i++)
{
thisSum += a[i];
if (thisSum > maxSum)
maxSum = thisSum;
else if (thisSum < 0)
thisSum = 0;
}
return maxSum;
}
`

{{ o.content }}

{{ i }}
1 ...
{{ i }}
{{ i }}