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?- A. 7
- B. 5
- C. 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
- Problem: Can s3 be formed by interleaving s1 and s2 (keeping each string's own order)? python def inter(s1, s2, s3): if len(s1) + len(s2)…
- Problem: Count palindromic substrings (by position, so equal strings at different places count separately) by expanding around every…
- Problem: Cut a rod of length 7 into integer pieces to maximise total price, where price[i] is the price of a piece of length i + 1…
- Problem: Envelopes [w, h] nest only if both dimensions are strictly smaller. Find the longest nesting chain by sorting and then running…
- Problem: Can the array be split into k subsets with equal sums? (Backtracking over bucket fills.) python def can(a, k): s = sum(a) if s %…
- Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c. python def flips(a, b, c): res = 0 while a or b or…