题解 | #最长上升子序列(一)#

最长上升子序列(一)

https://www.nowcoder.com/practice/5f65ccbb025240bd8458eb6479c2612e

定义dp[i] : 以i结尾的最长上升子序列长度

状态转移 : dp[i] = Math.max(dp[i],dp[j](j->(0,i-1)+1); 并且是arr[i] > arr[j] 的情况下才能转移

初始化dp[i] 都为1 因为他们自己本身就是一个最长上升子序列

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if(n==0){
            System.out.println(0);
            return;
        }
        int[] arr = new int[n];
        for(int i = 0;i<n;i++){
            arr[i] = sc.nextInt();
        }
        //dp[i] : 以i结尾的最长上升子序列长度
        int ans = 1;
        int[] dp = new int[n];
        Arrays.fill(dp,1);
        for(int i = 1;i<n;i++){
            for(int j = 0;j<i;j++){
                if(arr[i]>arr[j]){
                    dp[i] = Math.max(dp[i],dp[j]+1);
                }
            }
            ans = Math.max(ans,dp[i]);
        }
        System.out.println(ans);
    }
}

全部评论

相关推荐

LZHR:老哥你从投递简历测评完到一面中间隔了多久呀,我这边已经过了五天了仍显示简历筛选中是不是就是挂了
腾讯求职进展汇总
点赞 评论 收藏
分享
03-04 22:09
已编辑
南昌大学 golang
西北上单:29届? 请你去三角洲猛攻
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务