Data Structures & AlgorithmsModerateTCS NQT · DP warm-up

Problem: What is the maximum sum of a path from the top-left to the bottom-right of the grid [[1,3,1],[1,5,1],[4,2,1]] moving only right or down? Use the DP code.

Problem: What is the maximum sum of a path from the top-left to the bottom-right of the grid [[1,3,1],[1,5,1],[4,2,1]] moving only right or down? Use the DP code.
g = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
n, m = len(g), len(g[0])
dp = [[0] * m for _ in range(n)]
for i in range(n):
    for j in range(m):
        best = 0
        if i:
            best = max(best, dp[i - 1][j])
        if j:
            best = max(best, dp[i][j - 1])
        dp[i][j] = g[i][j] + best
print(dp[-1][-1])
What is printed?
  1. A. 10
  2. B. 12
  3. C. 11
  4. D. 9

Correct answer: B. 12

The best route is 1, 3, 5, 2, 1 with sum 12. The route 1, 1, 5, 2, 1 gives 10 and is the trap for choosing the wrong neighbour.

More Coding Interview Problems questions

Exams that ask this topic