You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Solutions to Chapter 9 | Sorting and Searching<br />
9 7 A circus is designing a tower routine consisting of people standing atop one ano<strong>the</strong>r’s<br />
shoulders For practical and aes<strong>the</strong>tic reasons, each person must be both shorter<br />
and lighter than <strong>the</strong> person below him or her Given <strong>the</strong> heights and weights of each<br />
person in <strong>the</strong> circus, write a method to compute <strong>the</strong> largest possible number of people<br />
in such a tower<br />
1 8 5<br />
EXAMPLE:<br />
Input (ht, wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110)<br />
Output: The longest tower is length 6 and includes from top to bottom: (56, 90)<br />
(60,95) (65,100) (68,110) (70,150) (75,190)<br />
SOLUTION<br />
<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts and Algorithms<br />
pg 66<br />
Step 1 Sort all items by height first, and <strong>the</strong>n by weight This means that if all <strong>the</strong> heights are<br />
unique, <strong>the</strong>n <strong>the</strong> items will be sorted by <strong>the</strong>ir height If heights are <strong>the</strong> same, items will be<br />
sorted by <strong>the</strong>ir weight<br />
Example:<br />
» Before sorting: (60, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68,110)<br />
» After sorting: (56, 90), (60, 95), (60,100), (68, 110), (70,150), (75,190)<br />
Step 2 Find <strong>the</strong> longest sequence which contains increasing heights and increasing<br />
weights<br />
To do this, we:<br />
a) Start at <strong>the</strong> beginning of <strong>the</strong> sequence Currently, max_sequence is empty<br />
b) If, for <strong>the</strong> next item, <strong>the</strong> height and <strong>the</strong> weight is not greater than those of <strong>the</strong> previous<br />
item, we mark this item as “unfit”<br />
(60,95) (65,100) (75,80) (80, 100)<br />
(unfit item)<br />
c) If <strong>the</strong> sequence found has more items than “max sequence”, it becomes “max sequence”<br />
d) After that <strong>the</strong> search is repeated from <strong>the</strong> “unfit item”, until we reach <strong>the</strong> end of <strong>the</strong> original<br />
sequence<br />
1 public class Question {<br />
2 ArrayList items;<br />
3 ArrayList lastFoundSeq;<br />
4 ArrayList maxSeq;<br />
5