You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. Find the longest chain which can be formed from a given set of pairs.
Source:Amazon Interview | Set 2
For example, if the given pairs are {{5, 24}, {39, 60}, {15, 28}, {27, 40}, {50, 90} }, then the longest chain that can be formed is of length 3, and the chain is {{5, 24}, {27, 40}, {50, 90}}
This problem is a variation of standardLongest Increasing Subsequenceproblem. Following is a simple two step process.
1) Sort given pairs in increasing order of first (or smaller) element.
2) Now run a modified LIS process where we compare the second element of already finalized LIS with the first element of new LIS being constructed.
本文介绍了一种寻找最长数对链的问题,该问题是在一系列给定的数对中找到最长的可以形成链的数对序列。文章提供了两种解决方法:一种是使用动态规划法,其时间复杂度为O(n*n);另一种是采用贪心算法,其效率更高,主要时间消耗来自于排序过程(O(nlgn))。通过具体的代码示例展示了这两种算法的具体实现。
620

被折叠的 条评论
为什么被折叠?



