算法导论(第三版) Exercises4.2(求最大和子数组的算法优化过程)

时间:2023-03-08 17:46:35

4.1-1

如所有元素都为负,则返回所有元素中最大的负数。

4.1-2(暴力法求最大和子数组)

struct subarray
{
int start, end, sum;
};
void bruteFindMaxSubarray(int a[], int left, int right, struct subarray* result)
{
int i, j, sum=a[left];
int tempSum;
int l = left;
int r = l;
for(i=left; i<=right; i++)
{
tempSum = a[i];
for(j=i+; j<=right; j++)
{
tempSum += a[j];
if(tempSum > sum)
{
l = i;
r = j;
sum = tempSum;
}
}
}
result->start = l;
result->end = r;
result->sum = sum;
}

4.1-3(归并算法求最大和子数组)

int mergeFindSub(int a[], int l, int r, int result[])
{
int i, j, k, mid;
int leftSum = ;
int rightSum = ;
int crossSum = ;
int leftResult[] = {};
int rightResult[] = {};
int crossResult[] = {};
if(l == r)
{
result[] = l;
result[] = r;
result[] = a[l];
}
else
{
mid = (l + r) / ;
leftSum = mergeFindSub(a, l, mid, leftResult);
rightSum = mergeFindSub(a, mid+, r, rightResult);
crossSum = crossingSub(a, l, mid, r, crossResult);
if(leftSum >= rightSum && leftSum >= crossSum)
for(i=; i<; i++) result[i] = leftResult[i];
else if(rightSum >= leftSum && rightSum >= crossSum)
for(j=; j<; j++) result[j] = rightResult[j];
else
for(k=; k<; k++) result[k] = crossResult[k];
}
return result[];
} int crossingSub(int a[], int l, int m, int r, int result[])
{
int i, j, leftSum, rightSum, sum;
int min = -;
rightSum = min;
leftSum = min;
sum = ;
for(i=m; i>=l; i--)
{
sum += a[i];
if(sum > leftSum)
{
result[] = i;
leftSum = sum;
}
}
sum = ;
for(j=m+; j<=r; j++)
{
sum += a[j];
if(sum > rightSum)
{
result[] = j;
rightSum = sum;
}
}
result[] = leftSum + rightSum;
return result[];
}

4.1-4

如果允许空串,只要加一句

if (sum < 0)  return sum=0;

4.1-5(线性算法求最大和字串)

void linearFindSub(int a[], int n, int result[])
{
int i, l, temp, sum;
int min = -;
sum = min;
temp = ;
l = ;
for(i=; i<n; i++)
{
if(temp < )
{
temp = a[i];
l = i;
}
else
temp += a[i];
if(sum < temp)
{
result[] = l;
result[] = i;
sum = temp;
}
}
result[] = sum;
}