Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the maximum number of points you can collect in a grid going right/down from top-left to bottom-right and then reconstruct which direction the last move was.

Problem: Find the maximum number of points you can collect in a grid going right/down from top-left to bottom-right and then reconstruct which direction the last move was.
g = [[1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2]]
R, C = 4, 4
dp = [[0] * C for _ in range(R)]
for r in range(R):
    for c in range(C):
        best = max(dp[r-1][c] if r else 0, dp[r][c-1] if c else 0) if (r or c) else 0
        dp[r][c] = g[r][c] + best
last = 'down' if dp[R-2][C-1] >= dp[R-1][C-2] else 'right'
print(dp[R-1][C-1], last)
What is printed?
  1. A. 17 right
  2. B. 18 down
  3. C. 15 down
  4. D. 17 down

Correct answer: D. 17 down

dp[r][c] = g[r][c] + max(from above, from the left). The last column's dp values are 10, 11, 15, 17 and the last row's 8, 14, 15, 17, so the bottom-right cell is 2 + max(15, 15) = 17. The two predecessors tie at 15, and the >= in the reconstruction picks 'down' (coming from above). Path reconstruction must define tie-breaking explicitly. O(R·C).

More Coding Interview Problems questions

Exams that ask this topic