zoukankan      html  css  js  c++  java
  • 【编程之美】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("
    ");
        printf("the input array is: ");
        for(int i = 0; i < alen; i++)
        {
            printf("%d ", a[i]);
        }
        printf("
    ");
        printf("the max increase sub array is: ");
        for(int i = maxid; i < alen;)
        {
            printf("%d ", a[i]);
            i = next[i];
        }
        printf("
    ");
        printf("the max increase sub array length is: %d
    ", max);
    }
    
    
    int main()
    {
        int a[8] = {1, -1, 2, -3, 4, -5, 6, -7};
        getMaxAscendSubArray(a, 8);
    
        return 0;
    }
  • 相关阅读:
    Win10 开启IIS后,访问“localhost”,报错无“C:WindowsMicrosoft.NETFramework64v4.0.30319Temporary ASP.NET Files”写访问权限
    使用pip安装Python扩展包时,如何提高速度?
    Django之路由层
    第一个Django项目
    Django简介
    DIY一个Web框架
    http协议
    Web应用和Web框架
    Python递归的经典案例
    Python修改文件的两种方法
  • 原文地址:https://www.cnblogs.com/dplearning/p/4092242.html
Copyright © 2011-2022 走看看