ProgrammingHardGATE CS & IT · Infosys
What is printed?
What is printed?
def rob(a):
p, c = 0, 0
for x in a:
p, c = c, max(c, p + x)
return c
print(rob([2, 7, 9, 3, 1]), rob([5]), rob([]))- A. 11 5 0
- B. 12 5 0
- C. 12 5 5
- D. 12 0 0
Correct answer: B. 12 5 0
The best non-adjacent subset of [2,7,9,3,1] is 2 + 9 + 1 = 12. Empty input gives 0 and a single item gives its own value.
More Python Programming questions
- What is printed? python def ed(a, b): prev = list(range(len(b) + 1)) for i in range(1, len(a) + 1): cur = [i] + [0] len(b) for j in…
- What is printed? python def minlen(a, t): best = float('inf') s = 0 l = 0 for r, x in enumerate(a): s += x while s >= t: best = min(best…
- What is printed? python import heapq def kthlargest(a, k): h = [] for x in a: heapq.heappush(h, x) if len(h) > k: heapq.heappop(h) return…
- What is printed? python from collections import deque def winmax(a, k): dq = deque() out = [] for i, x in enumerate(a): while dq and…
- What is printed? python from collections import deque g = {1: [2, 3], 2: [4], 3: [4, 5], 4: [6], 5: [], 6: []} dist = {1: 0} q =…
- What is printed? python from functools import cache @cache def total(xs): return sum(xs) try: print(total((1, 2, 3))) print(total([1, 2…