27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Solutions</strong> to Chapter 9 | Sorting <strong>and</strong> Searching<br />

6 // Returns longer sequence<br />

7 ArrayList seqWithMaxLength(ArrayList seq1,<br />

8 ArrayList seq2) {<br />

9 return seq1.size() > seq2.size() ? seq1 : seq2;<br />

10 }<br />

11<br />

12 // Fills next seq w decreased wts&returns index of 1st unfit item.<br />

13 int fillNextSeq(int startFrom, ArrayList seq) {<br />

14 int firstUnfitItem = startFrom;<br />

15 if (startFrom < items.size()) {<br />

16 for (int i = 0; i < items.size(); i++) {<br />

17 HtWt item = items.get(i);<br />

18 if (i == 0 || items.get(i-1).isBefore(item)) {<br />

19 seq.add(item);<br />

20 } else {<br />

21 firstUnfitItem = i;<br />

22 }<br />

23 }<br />

24 }<br />

25 return firstUnfitItem;<br />

26 }<br />

27<br />

28 // Find <strong>the</strong> maximum length sequence<br />

29 void findMaxSeq() {<br />

30 Collections.sort(items);<br />

31 int currentUnfit = 0;<br />

32 while (currentUnfit < items.size()) {<br />

33 ArrayList nextSeq = new ArrayList();<br />

34 int nextUnfit = fillNextSeq(currentUnfit, nextSeq);<br />

35 maxSeq = seqWithMaxLength(maxSeq, nextSeq);<br />

36 if (nextUnfit == currentUnfit) break;<br />

37 else currentUnfit = nextUnfit;<br />

38 }<br />

39 }<br />

40 }<br />

CareerCup.com<br />

1 8 6

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!