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 20 | Hard<br />

Val_D = area(point(0, 0) -> point(x2, y2))<br />

Val_C = area(point(0, 0) -> point(x2, y1))<br />

Val_B = area(point(0, 0) -> point(x1, y2))<br />

Val_A = area(point(0, 0) -> point(x1, y1))<br />

With <strong>the</strong>se values, we know <strong>the</strong> following:<br />

area(D) = Val_D - area(A union C) - area(A union B) + area(A).<br />

Or, written ano<strong>the</strong>r way:<br />

area(D) = Val_D - Val_B - Val_C + Val_A<br />

Can we efficiently compute <strong>the</strong>se Val_* values for all points in <strong>the</strong> matrix? Yes, by using similar<br />

logic:<br />

Val_(x, y) = Val(x - 1, y) + Val(y - 1, x) - Val(x - 1, y - 1)<br />

We can precompute all such values, <strong>and</strong> <strong>the</strong>n efficiently find <strong>the</strong> maximum submatrix. See<br />

<strong>the</strong> following code for this implementation<br />

1 public static int getMaxMatrix(int[][] original) {<br />

2 int maxArea = Integer.MIN_VALUE; // Important! Max could be < 0<br />

3 int rowCount = original.length;<br />

4 int columnCount = original[0].length;<br />

5 int[][] matrix = precomputeMatrix(original);<br />

6 for (int row1 = 0; row1 < rowCount; row1++) {<br />

7 for (int row2 = row1; row2 < rowCount; row2++) {<br />

8 for (int col1 = 0; col1 < columnCount; col1++) {<br />

9 for (int col2 = col1; col2 < columnCount; col2++) {<br />

10 maxArea = Math.max(maxArea, computeSum(matrix,<br />

11 row1, row2, col1, col2));<br />

12 }<br />

13 }<br />

14 }<br />

15 }<br />

16 return maxArea;<br />

17 }<br />

18<br />

19 private static int[][] precomputeMatrix(int[][] matrix) {<br />

20 int[][] sumMatrix = new int[matrix.length][matrix[0].length];<br />

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

22 for (int j = 0; j < matrix.length; j++) {<br />

23 if (i == 0 && j == 0) { // first cell<br />

24 sumMatrix[i][j] = matrix[i][j];<br />

25 } else if (j == 0) { // cell in first column<br />

26 sumMatrix[i][j] = sumMatrix[i - 1][j] + matrix[i][j];<br />

27 } else if (i == 0) { // cell in first row<br />

28 sumMatrix[i][j] = sumMatrix[i][j - 1] + matrix[i][j];<br />

29 } else {<br />

30 sumMatrix[i][j] = sumMatrix[i - 1][j] +<br />

31 sumMatrix[i][j - 1] - sumMatrix[i - 1][j - 1] +<br />

CareerCup.com<br />

2 9 6

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

Saved successfully!

Ooh no, something went wrong!