Longest chain of pairs

后端 未结 5 639
面向向阳花
面向向阳花 2021-02-04 10:16

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

5条回答
  •  我在风中等你
    2021-02-04 11:05

    It seems to me that one characteristic of the longest chain is that it minimizes the total span of any two adjacent tuples (to maximize the number of possible tuples for any range).

    In that case, as Brian Stephens suggested, we need only sort by the second number, ascending (to guarantee the smallest span when searching for the next tuple), and build the chain starting with the first tuple in the sorted list.

    We can prove that this solution is optimal by positing that if S(0) is the chain starting on the first tuple, there exists an S(i), where i is not in S(0), that is longer than S(0); and therefore also a chain S(i+1) that is longer than S(1). We know that the start of i must be before the end of i-1 or it would have been included in S(0). Now if the end of i-1 were equal to the end of i, S(i+1) would be part of S(0), which contradicts our premise. Alternatively, if the end of i were greater than the end of i-1, again S(i+1) would be included in S(0). The end of i could not be less than the end of i-1 since the list is sorted by this property.

提交回复
热议问题