Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: A knight walks from the top-left to the bottom-right cell moving only right or down; each cell adds its value to his health, which must stay ≥ 1 at all times. What minimum starting health is needed?

Problem: A knight walks from the top-left to the bottom-right cell moving only right or down; each cell adds its value to his health, which must stay ≥ 1 at all times. What minimum starting health is needed?
def need(g):
    R, C = len(g), len(g[0])
    dp = [[float('inf')] * (C + 1) for _ in range(R + 1)]
    dp[R][C-1] = dp[R-1][C] = 1
    for r in range(R - 1, -1, -1):
        for c in range(C - 1, -1, -1):
            dp[r][c] = max(1, min(dp[r+1][c], dp[r][c+1]) - g[r][c])
    return dp[0][0]
print(need([[0, -4, 2], [-3, 5, -6], [1, -2, -1]]))
What is printed?
  1. A. 7
  2. B. 5
  3. C. 4
  4. D. 1

Correct answer: C. 4

The DP runs backwards: dp[r][c] is the health needed on entering (r, c). Forward greedy fails because a path with a better final sum can dip lower on the way. The best route needs 4, matching a check of all 6 routes.

More Coding Interview Problems questions

Exams that ask this topic