Data Structures & AlgorithmsHardProduct Company SDE · DP round
Problem: Houses in a circle hold the amounts [2, 3, 2]. You may not rob two adjacent houses, and the first and last are adjacent. Run the code. What is printed?
Problem: Houses in a circle hold the amounts [2, 3, 2]. You may not rob two adjacent houses, and the first and last are adjacent. Run the code. What is printed?
def rob_line(a):
p = q = 0
for x in a:
p, q = q, max(q, p + x)
return q
a = [2, 3, 2]
print(max(rob_line(a[:-1]), rob_line(a[1:])))What is printed?- A. 3
- B. 4
- C. 5
- D. 2
Correct answer: A. 3
Robbing the first and last house together is forbidden, so the answer is the better of the two linear problems: [2, 3] gives 3 and [3, 2] gives 3. Robbing 2 + 2 = 4 would break the adjacency rule.
More Coding Interview Problems questions
- Problem: What is the length of the longest common subsequence of 'ABCBDAB' and 'BDCABA'? python a, b = 'ABCBDAB', 'BDCABA' dp = [[0]…
- Problem: The number of structurally distinct binary search trees on 5 keys is the Catalan number. What does this code print? python dp =…
- Problem: What is the sum over all pairs (i < j) of the Hamming distances (number of differing bits) between the values in [1, 3, 5]? Run…
- Problem: People with weights [3, 2, 2, 1] must cross a river. A boat carries at most 2 people with total weight at most limit = 3, and…
- Problem: Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. She picks one pile per hour and eats up to k bananas from it…
- Problem: How many primes are there up to 100? Run the sieve. python n = 100 sieve = [True] (n + 1) sieve[0] = sieve[1] = False for i in…