【编程之美】2.16 求数组的最大递增子序列

如 1  -1  2  -3  4  -5  6  -7的最大递增子序列为 1  2  4  6

思路:动态规划 从后向前 存储下一个递增元素的位置 和以当前数字为首的递增子序列的长度

答案中说可以用O(NlogN)我没看懂

#include <stdio.h>
#include<stdlib.h>

//下面解法的时间复杂度 O(N^2)
void getMaxAscendSubArray(int * a, int alen)
{
    int * next = (int *)calloc(alen, sizeof(a[0])); //存储当前元素的下一个递增数字的下标
    int * count = (int *)calloc(alen, sizeof(a[0])); //存储以当前数字为首的子序列中 最大递增子序列的长度

    //动态规划 从后往前
    for(int i = alen - 1; i >= 0; i--)
    {
        next[i] = alen;
        count[i] = 1;
        for(int j = i + 1; j < alen; j++)
        {
            if(a[j] > a[i])
            {
                next[i] = j;
                count[i] += count[j];
                break;
            }
        }
    }

    //找到长度最大的下标
    int max = 0;
    int maxid = 0;
    for(int i = 0; i < alen; i++)
    {
        if(count[i] > max)
        {
            max = count[i];
            maxid = i;
        }
    }

    //输出
    printf("\n");
    printf("the input array is: ");
    for(int i = 0; i < alen; i++)
    {
        printf("%d ", a[i]);
    }
    printf("\n");
    printf("the max increase sub array is: ");
    for(int i = maxid; i < alen;)
    {
        printf("%d ", a[i]);
        i = next[i];
    }
    printf("\n");
    printf("the max increase sub array length is: %d\n", max);
}


int main()
{
    int a[8] = {1, -1, 2, -3, 4, -5, 6, -7};
    getMaxAscendSubArray(a, 8);

    return 0;
}

 

posted @ 2014-11-12 14:41  匡子语  阅读(333)  评论(0编辑  收藏  举报