求最大子序列的算法

来源:互联网 发布:perl语言编程 第四版 编辑:程序博客网 时间:2024/05/25 01:35
问题:
给定一个序列,求它的一个连续子序列,使其值在所有子序列中最大,每个元素可以为负数。
    
分析:
用归纳法,当我们知道了(X1 X2 … Xi-1)的最大序列后,那么加入Xi后会需要考虑两种情况:第一,原来的最大值不受影响;第二,包括Xi的后缀序列成了最大值,因此我们在遍历的过程中,需要保留这两个最大值。
                           
#include <stdio.h>
#include <stdlib.h>
     
double find_subserial(double x[],int n)
{
    double global_max = 0;                   //save the global max value
    double suffix_max = 0;                     //save the suffix max value
    int i;
    for(i=0;i<n;i++)
    {
        if( suffix_max + x[i] > global_max)
        {
            global_max = suffix_max = suffix_max + x[i];
        }
        else if( suffix_max + x[i] > 0 )
        {
            suffix_max = suffix_max+x[i];
        }
        else
        {
            suffix_max = 0;
        }
    }
    return global_max;
}
    
int main(int argc,char * argv[])
{
    double * temp;
    int i;
    temp = (double *)malloc( (argc-1) * sizeof(double) );
    for(i=1;i<argc;i++)
    {
        temp[i-1] = atof(argv[i]);
        printf("%g ",temp[i-1]);
    }
    printf("/n");
    printf("The max is %g /n",find_subserial(temp,argc-1));
    return 0;
}
原创粉丝点击