1、最大子串问题描述:
给定一个指定长度的整型数组A,求其中和最大的子串。
网上有很多算法,穷举、分治、线性回归。我觉得有点麻烦。
2、算法
一个数组A,要找其中最大的子串,我们可以从第一个数A[0]开始,往后累加存放和在currentSum里面,如果currentSum小于0了,我们可以抛弃,不再往后累加了,(因为是负数了,往后累加肯定不是最大了)。然后保存前面我们累加的最大子串。然后从下一个位置开始重复这个过程。最后将这写保存的最大子串的和进行比较。最大的就是我们需要的。
3、举例:
A[8]={4,5,-9,5,3,0,-50,3}
首先,从4开始,currentSum = 4,向后累加一次,currentSum = 9,继续,currentSum = 0,继续,currentSum = 5,继续,currentSum = 8,继续,currentSum = 8,继续,currentSum = -42,小于0了。这时候我们保存之前的最大9的子串,清空这一切,从3开始重复这个过程,currentSum = 3,结束了。于是保存这一次的累加的最大子串,然后比较这两次的子串大小。最后得出我们需要的结果。
4、算法复杂度
O(n),但是这个比较耗费空间。
5、我用链表保存结果,数组的长度是16,代码如下:
#include<stdio.h>
#include<stdlib.h>
#define NUM 16
typedef struct info{
int first;
int end;
int n;
int max;
struct info *next;
}info;
/*
*initialization
*
*/
void init(info *in)
{
in->first = 0;
in->end = -1;
in->n = 0;
in->max = 0;
in->next = NULL;
}
/*
*search the longest sub,and keep it in the link.
*/
int sub()
{
int currentMax,i;
info *fir,*head,*sec;
head = (info*)malloc(sizeof(info));
fir = head;
int test[NUM] = {4,5,-9,5,3,10,-50,6,3,0,3,5,1,5,-9,13};
currentMax = 0;
init(head);
for(i = 0;i < NUM; i++)
{
currentMax += test[i];
if(currentMax < 0)
{
sec = (info *)malloc(sizeof(info));
fir->next = sec;
fir = sec;
fir->first = i+1;
fir->n = 0;
fir->max = 0;
fir->next = NULL;
fir->end = i+1;
currentMax = 0;
}
if(currentMax > fir->max)
{
fir->max = currentMax;
fir->end = i;
}
}
show(head);
return 1;
}
/*
*filter the result
*/
int outprint(info *);
int show(info *head)
{
info *phead,*res;
res = phead = head;
int fmax;
fmax = phead->max;
for(phead = head->next;phead != NULL;phead = phead->next)
{
if(fmax < phead->max)
{
fmax = phead->max;
res = phead;
}
}
outprint(res);
return 1;
}
/*
*output the final result
*/
int outprint(info *res)
{
printf("--------------------------------\n");
printf("the longest sub is:\n");
printf("from the place of %d to %d\n",res->first,res->end);
printf("the max is %d\n",res->max);
return 1;
}
int main()
{
sub();
}
在linux下面运行结果如下:
-------------------------------------------------
the longest sub is:
from the place of 7 to 15
the max is 27
实验室的师姐师兄开始找实习,那些招聘的公司,看算法看的紧啊。平时还是要多积累了。