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?- A. 10
- B. 12
- C. 11
- 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
- Problem: How many binary strings of length 5 contain no two consecutive 1s?
- Problem: What is the maximum product of a non-empty contiguous subarray of [2, 3, -2, 4, -1]? Use the code below. python a = [2, 3, -2, 4…
- Problem: How many islands (4-connected groups of '1') are in the grid below? Run the DFS code. python g = ['11000', '11000', '00100'…
- Problem: How many subarrays of [1, -1, 2, -2, 3, -3] have sum zero? Run the prefix-count code. python from collections import Counter a =…
- Problem: A data stream needs the median of the last k elements. Which structure supports each slide in O(log k) time?
- Problem: Consider a connected undirected graph whose edge weights are all distinct. Which statement is true?