求最大子序列
一直以来我有个错误的观点,就是数据结构和算法只要学习那些平时工作最常用的就可以了。这是典型的找借口行为。所以我打算开始认真复习好数据结构和算法,我目前熟悉的算法其实只有链表和动态数组,真是可悲。
Mark Allen Weiss那本《数据结构与算法分析》第二章,求最大子序列:-2 11 -4 13 -5 -2 最大子序列为20(11到13)。
题目不难,我也还没有看答案。目前我有个简单的想法:先求出序列的最大值是什么,这个只能花 O(N)来遍历了。接下来,把最大值的下标作为开始地址,把最大值往左边依次叠加,如果发现大于最大值则更新最大值,直到下标为0;最后同样道理往右边叠加,得出最大子序列值。话的时间是O(N),当然不是最优的。下面写出代码:
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXCOUNT 100
int maxNumberIndex(const int *arr, const int size)
{
int maxIndex = 0;
int max = arr[0];
for (int index = 1; index < size; ++index)
{
if (arr[index] > max)
{
max = arr[index];
maxIndex = index;
}
}
return maxIndex;
}
int maxSubList(const int *arr, const int size)
{
int maxIndex = maxNumberIndex(arr, size);
int max = arr[maxIndex];
int temp = max;
for (int i = maxIndex - 1; i >= 0; --i)
{
temp += arr[i];
if (temp > max)
{
max = temp;
}
}
temp = max;
for (int j = maxIndex + 1; j < size; ++j)
{
temp += arr[j];
if (temp > max)
{
max = temp;
}
}
return max;
}
void display(const int *arr, const int size)
{
for (int index = 0; index < size; ++index)
{
printf("%3d ", arr[index]);
}
printf("\n");
}
int main(void)
{
int arr[MAXCOUNT] = {0};
srand( (unsigned int)time(NULL) );
for (int i = 0; i < MAXCOUNT; ++i)
{
arr[i] = rand() % 100 - 60;
}
display(arr, MAXCOUNT);
printf("the max sub list is %d.\n", maxSubList(arr, MAXCOUNT) );
return 0;
}
===============================================================
9月15日更新:好吧,是我想得太简单了。最大子序列的值并不一定包含数组中最大的那个值:-(