646. Maximum Length of Pair Chain

You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.

Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.

Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order.

Example 1:

Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]

 Note:

  1. The number of given pairs will be in the range [1, 1000].

题目含义:给定一组数对,我们定义当且仅当b < c时,(c, d)可以链在(a, b)之后。求可以组成的最长数对链的长度。

 

复制代码
 1     public int findLongestChain(int[][] pairs) {
 2 //        p[i]储存的是从i结束的链表长度最大值。首先初始化每个dp[i]为1。然后对于每个dp[i],找在 i 前面的索引 0~j,
 3 //        如果存在可以链接在i 前面的数组,且加完后大于dp[i]之前的值,那么则在dp[j]的基础上+1.
 4         Arrays.sort(pairs, (a, b) -> (a[0] - b[0]));
 5         int i, j, max = 0, n = pairs.length;
 6         int dp[] = new int[n];
 7         Arrays.fill(dp,1);
 8         for (i = 1; i < n; i++)
 9             for (j = 0; j < i; j++)
10                 if (pairs[j][1] < pairs[i][0] && dp[i] < dp[j] + 1)
11                     dp[i] = dp[j] + 1;
12 
13         for (i = 0; i < n; i++) if (max < dp[i]) max = dp[i];
14         return max;        
15     }
复制代码

 

posted @   daniel456  阅读(113)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示