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

最长上升子序列(一)

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] nums = new int[n];
        int index = 0;
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            nums[index] = a;
            index++;
        }
        int[] dp = new int[n];
        Arrays.fill(dp,1);
        int res = dp[0];
        for(int i = 1; i < n; i++){
            for(int j = 0; j < i; j++){
                // i指向当前序列的最后位置,来统计这个位置之前所有这个位置小的个数
                if(nums[i] > nums[j]){
                    dp[i] = Math.max(dp[i],dp[j] + 1);
                }
                res = Math.max(res, dp[i]);
            }
        }
        System.out.println(res);
    }
}

全部评论

相关推荐

双尔:反手回一个很抱歉,经过慎重考虑,您与我的预期暂不匹配,感谢您的投递
点赞 评论 收藏
分享
刷牛客的单身狗很认真:全国可飞,支持007 上班时间,是吧?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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