最大子序列

2008-7-2 Jerry 开发

给定一个数组,当中有正负数,求当中的一段“子数组”(即任意长度,连续的数字),使得这个“子数组”的和是所有“子数组”和中最大的,如给定的数组为12, -8, 5, 66, -21, 0, 35, -44, 7,则最大的和的子数组为{12, -8, 5, 66, -21, 0, 35},最大的和为89。

C# 实现。MaxSubSum.cs:

[code]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace submax
{
class MaxSubSum
{
// o(n3)
public static int MaxSubSum1(int[] a)
{
int maxSum = 0;
for (int i = 0; i < a.Length; i++)
{
for (int j = i; j < a.Length; j++)
{
int thisSum = 0;

for (int k = i; k <= j; k++)
thisSum += a[k];

if (thisSum > maxSum)
maxSum = thisSum;
}
}

return maxSum;
}

// o(n2)
public static int maxSubSum2(int[] a)
{
int maxSum = 0;

for (int i = 0; i < a.Length; i++)
{
int thisSum = 0;
for (int j = i; j < a.Length; j++)
{
thisSum += a[j];
if (thisSum > maxSum)
maxSum = thisSum;
}
}
return maxSum;
}

// o(nlogn)
private static int maxSumRec(int[] a, int left, int right)
{
if (left == right) // Base case
if (a[left] > 0)
return a[left];
else
return 0;

int center = (left + right) / 2;
int maxLeftSum = maxSumRec(a, left, center);
int maxRightSum = maxSumRec(a, center + 1, right);

int maxLeftBorderSum = 0, leftBorderSum = 0;
for (int i = center; i >= left; i--)
{
leftBorderSum += a[i];
if (leftBorderSum > maxLeftBorderSum)
maxLeftBorderSum = leftBorderSum;
}

int maxRightBorderSum = 0, rightBorderSum = 0;
for (int i = center + 1; i < right; i++)
{
leftBorderSum += a[i];
if (rightBorderSum > maxRightBorderSum)
maxRightBorderSum = rightBorderSum;
}

return max3(maxLeftSum, maxRightSum, maxLeftBorderSum
+ maxRightBorderSum);
}

private static int max3(int a, int b, int c)
{
if (a > b)
{
if (a > c)
return a;
else
return c;
}
else
{
if (b > c)
return b;
else
return c;
}
}


public static int maxSubSum3(int[] a)
{
return maxSumRec(a, 0, a.Length - 1);
}

// o(n)
public static int maxSubSum4(int[] a)
{
int maxSum = 0, thisSum = 0;

for (int j = 0; j < a.Length; j++)
{
thisSum += a[j];
if (thisSum > maxSum)
maxSum = thisSum;
else if (thisSum < 0)
thisSum = 0;
}

return maxSum;
}

}
}

[/code]


发表评论:

Powered by emlog sitemap