ProgrammingHardCodeforces-style · placement coding round
What is printed?
What is printed?
def min_path(g):
dp = [0] * len(g[0])
for i, row in enumerate(g):
for j, v in enumerate(row):
if i == 0 and j == 0:
dp[j] = v
elif i == 0:
dp[j] = dp[j - 1] + v
elif j == 0:
dp[j] = dp[j] + v
else:
dp[j] = min(dp[j], dp[j - 1]) + v
return dp[-1]
print(min_path([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))- A. 7
- B. 9
- C. 12
- D. 21
Correct answer: A. 7
The rolling dp keeps the cheapest cost to each column: the route 1 → 3 → 1 → 1 → 1 costs 7. Greedily stepping to the smaller neighbour costs 9, the most expensive right/down route is 12, and 21 is the sum of the whole grid.
More Python Programming questions
- What is printed? python from functools import lrucache def wb(s, words): @lrucache(maxsize=None) def go(i): if i == len(s): return 1…
- What is printed? python from functools import cache @cache def ways(s, i=0): if i == len(s): return 1 if s[i] == '0': return 0 total =…
- What is printed? python import heapq words = ['bb', 'a', 'cc', 'dd', 'e'] print(heapq.nlargest(2, words, key=len), heapq.nsmallest(2…
- What is printed? python data = [3, 8, 15, 4, 22] res = [y for x in data if (y := x 2) > 20] print(res, y)
- A sorted array holds 10^6 integers and receives 10^5 queries asking how many values are at most x. Which approach is fastest in CPython?
- What is printed? python def depth(n): return 0 if n == 0 else 1 + depth(n - 1) try: print(depth(500)) print(depth(5000)) except…