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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 19 | Moderate<br />

19.7 You are given an array of integers (both positive <strong>and</strong> negative). Find <strong>the</strong> continuous<br />

sequence with <strong>the</strong> largest sum. Return <strong>the</strong> sum.<br />

EXAMPLE<br />

SOLUTION<br />

Input: {2, -8, 3, -2, 4, -10}<br />

Output: 5 (i.e., {3, -2, 4} )<br />

pg 89<br />

A simple linear algorithm will work by keeping track of <strong>the</strong> current subsequence sum. If that<br />

sum ever drops below zero, that subsequence will not contribute to <strong>the</strong> subsequent maximal<br />

subsequence since it would reduce it by adding <strong>the</strong> negative sum.<br />

1 public static int getMaxSum(int[] a) {<br />

2 int maxsum = 0;<br />

3 int sum = 0;<br />

4 for (int i = 0; i < a.length; i++) {<br />

5 sum += a[i];<br />

6 if (maxsum < sum) {<br />

7 maxsum = sum;<br />

8 } else if (sum < 0) {<br />

9 sum = 0;<br />

10 }<br />

11 }<br />

12 return maxsum;<br />

13 }<br />

NOTE: If <strong>the</strong> array is all negative numbers, what is <strong>the</strong> correct behavior? Consider<br />

this simple array {-3, -10, -5}. You could make a good argument that <strong>the</strong><br />

maximum sum is ei<strong>the</strong>r: (A) -3 (if you assume <strong>the</strong> subsequence can’t be empty)<br />

(B) 0 (<strong>the</strong> subsequence has length 0) or (C) MINIMUM_INT (essentially <strong>the</strong> error<br />

case). We went with option B (max sum = 0), but <strong>the</strong>re’s no “correct” answer. This<br />

is a great thing to discuss with your interviewer to show how careful you are.<br />

2 7 3<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Additional Review Problems

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

Saved successfully!

Ooh no, something went wrong!