Cracking the Coding Interview, fourth edition , has this problem:
The circus designs a tower routine consisting of people standing on one shoulder. For practical and aesthetic reasons, each person should be both shorter and lighter than the person below him or her. Given the heights and weights of each person in the circus, write a way to calculate the maximum possible number of people in such a tower.
Example: Input (ht, wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110).Exit: the longest tower is length 6 and includes top to bottom: (56, 90) (60.95) (65 100) (68 110) (70,150) (75,190)
Here is his solution in the book
Step 1 First sort all the elements by height, and then by weight. This means that if all heights are unique, then the items will be sorted by their height. If the heights are the same, items will be sorted by their weight.
Step 2 Find the longest sequence that contains an increase in height and an increase in weight. To do this, we:
a) Start at start of sequence Currently max_sequence is empty
b) If for the next element the height and weight are not greater than the previous element, we mark this element as “unusable”
c) If the sequence found contains more elements than the "maximum sequence", it becomes the "maximum sequence"
d) After that, the search is repeated from the “unsuitable element” until we reach the end of the original sequence
I have some questions about his solutions.
Q1
I believe this decision is wrong.
for instance
(3,2) (5,9) (6,7) (7,8)
Obviously, (6,7) is unsuitable, but what about (7,8) ? According to the decision, it is NOT unsuitable, since its h and w are greater than (6,7) , but it cannot be considered in sequence, because (7,8) does not fit (5,9) .
I'm right?
If I am right, what is the fix?
Q2
I believe that even if there is a correction for the above solution, the style of the solution will lead to at least O(n^2) , because it needs to be repeated again and again, according to step 2-d.
So, is it possible to have an O (nlogn) solution?