求最长递增子序列(数组方法,其他方法未完待续)

给定一个顺序存储的线性表,请设计一个算法查找该线性表中最长的连续递增子序列。例如,(1,9,2,5,7,3,4,6,8,0)中最长的递增子序列为(3,4,6,8)。
输入格式:
输入第1行给出正整数n(\le 10^5≤10​5​​);;第2行给出n个整数,其间以空格分隔。

输入样例:
15
1 9 2 5 7 3 4 6 8 0 11 15 17 17 10
输出样例:
3 4 6 8

思路:首先寻找存在最长子序列的序列长度和终止下标,接下来按要求输出。

如果序列长度为0,则最长递增子序列为第一个元素。

链表法和动态规划法未完待续。

代码如下:

include<iostream>
using namespace std;
#define maxn 100005
int main()
{
    int n,count = 0;
    int a[maxn];
    scanf("%d",&n);
    for(int i = 0; i <n; i ++)
        scanf("%d",&a[i]);
    int i,j = 0,k;
    for(i = 1; i < n; i ++)
    {
        if(a[i]>a[i-1])
        {
                count++;
                if(count>j)
            {
                j = count;
                k = i;
            }
        }
        else
            count = 0;
    }
    int start = k - j;
    int end = k;
    if(j>0)
    {
        int flag = 0;
        
        for(int t = start; t <= end; t ++)
        {
            if(!flag)
            {
                printf("%d",a[t]);
                flag = 1;
            }
            else
                printf(" %d",a[t]);
        }
    }
    else
        printf("%d",a[0]);


    
    
 }

猜你喜欢

转载自blog.csdn.net/qiulianshaonv_wjm/article/details/82958877