Algorithms - find the largest and subsequence

Laboratory building work

Inputting a set of integers, the maximum value is obtained sequences and the set of numbers, as long as the largest sequence determined and, corresponding to the maximum sequence need not obtained.
And the maximum sequence: the sequence of integers A1, A2, ... An (there may be negative), seeking a sequence of A1An AiAj, such that Ai and Aj to the maximum.
For example:
the sequence: 2,2, 3,4,5,6. The maximum subsequence and 15.

Code

#include <stdio.h>

int main()
{
    int serial[] = {1,2,-3,4,5};//输入的序列
    int max_sum = 0;//子序列的最大的和
    int w,n;//w是外层循环,自子序列的第一个值;n是内层循环,在w的基础上加n,serial[w+n]就是子序列的第n个值
    for(w=0;w<5;w++)//外层循环,数组每个元素都做一次子序列头
    {
        int msum = 0;//临时变量,每个子序列的和
        for(n=0;n+w<5;n++)//在子序列的最后一个值,不超过数组最大下标时,就可以一直自加求和
        {
            msum += serial[w+n];
            
        }
        if(msum > max_sum)//如果有子序列和比之前的大,那就挑出最大的来
        {
            max_sum = msum;
        }
    }
    printf("the max_sum is %d",max_sum);//输出结果
   return 0;
}

Operation result

the max_sum is 9

Summary sentiment

To be honest, since the work has never been seriously algorithms and data structures, into the line more than six months, until September, then counted throughout the year.
Algorithms and Data Structures must fill up.
Today is a beginning, everything is hard in the beginning, just start the stick, you know the power of integration.
The above words very cliche, but really for the heart and soul, I also understand why so formulaic words, we often see people mention
that it is because of the heart and feel is natural.

Guess you like

Origin www.cnblogs.com/houser0323/p/11001360.html