Algorithm for Human Towering

后端 未结 4 1912
悲哀的现实
悲哀的现实 2021-01-02 22:39

In Cracking the Coding Interview, Fourth Edition, there is such a problem:

A circus is designing a tower routine consisting of people standing atop

4条回答
  •  孤独总比滥情好
    2021-01-02 22:53

    You can solve the problem with dynamic programming.

    Sort the troupe by height. For simplicity, assume all the heights h_i and weights w_j are distinct. Thus h_i is an increasing sequence.

    We compute a sequence T_i, where T_i is a tower with person i at the top of maximal size. T_1 is simply {1}. We can deduce subsequent T_k from the earlier T_j — find the largest tower T_j that can take k's weight (w_j < w_k) and stand k on it.

    The largest possible tower from the troupe is then the largest of the T_i.

    This algorithm takes O(n**2) time, where n is the cardinality of the troupe.

提交回复
热议问题