Longest chain of pairs

后端 未结 5 637
面向向阳花
面向向阳花 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 10:52

    Because the two values of each (X,Y) pair must be in order (X < Y), and the Y value of one pair must be less than the X value of the next pair, you are essentially building one continuous chain of values along one dimension. You just need to sort by the Y values.

    Given this sample data:

    (15,40) (5,8) (1,10) (6,8) (9,20) (2,4) (36,37) (34,35) (9,14) (30,31)
    

    Sort by Y to get:

    (2,4) (6,8) (5,8) (1,10) (9,14) (9,20) (30,31) (34,35) (36,37) (15,40)
    

    Then loop through, adding a pair to the chain if its X is greater than the last Y in the chain, and ignoring it otherwise.

    Notice that in this example, (6,8) happened to be sorted before (5,8). It doesn't matter which pair is chosen for the chain when their Y values are equal, as long as the X value satisfies the condition of being greater than the previous Y.

    Here's a diagram showing the sorted pairs as bars above a number line. Starting at the first pair, (2,4), each one that is added to the chain at the bottom is colored yellow. Visually, the gray ones are skipped because there's a yellow one "in the way" of it being dropped into the chain (overlapping values).

    diagram of sorted pairs

    Proof: The only way to include more pairs in the chain is to replace a pair with one with a smaller Y value, to allow for the next pair to have a smaller X value, potentially fitting another pair where it couldn't fit before. If you replace a pair with one with the same Y value, you gain nothing. If the replacement has a larger Y value, all you've done is potentially block some pairs that would've fit before.

    Because the pairs have been sorted by Y values, you will never find a replacement with a smaller Y. Looking "forward" in the sorted pairs, they will all have the same or greater Y value. Looking "backward", any that were eliminated from the chain initially were because the X value wasn't high enough, which will still be the case.

提交回复
热议问题