Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Same robbery, but the houses form a circle (first and last are adjacent).
Problem: Same robbery, but the houses form a circle (first and last are adjacent).
def line(a):
take = skip = 0
for x in a:
take, skip = skip + x, max(take, skip)
return max(take, skip)
def circle(a):
if len(a) == 1: return a[0]
return max(line(a[1:]), line(a[:-1]))
print(circle([2, 3, 2]), circle([1, 2, 3, 1]), circle([5]))What is printed?- A. 4 4 5
- B. 3 4 0
- C. 3 3 5
- D. 3 4 5
Correct answer: D. 3 4 5
Run the line version twice – once without the first house, once without the last – so the two ends are never both taken. [2, 3, 2] → 3 (not 2 + 2 = 4). [1, 2, 3, 1] → 1 + 3 = 4. A single house must be handled separately, otherwise both slices are empty and the answer becomes 0. O(n).
More Coding Interview Problems questions
- Problem: Find the fewest coins that make an amount (−1 if impossible). python def coins(cs, amt): INF = float('inf'); dp = [0] + [INF] amt…
- Problem: Count the number of ways to make an amount from unlimited coins, where order does not matter. python def ways(cs, amt): dp = [1]…
- Problem: 0/1 knapsack with a 1-D array. The candidate below loops capacity upwards. python def wrong(w, v, W): dp = [0] (W + 1) for i in…
- Problem: 0/1 knapsack – maximise value within capacity W. cpp int knap(vector<int> w, vector<int> v, int W) { vector<int> dp(W + 1, 0)…
- Problem: Find the length of the longest strictly increasing subsequence of daily sales. python from bisect import bisectleft def lis(a)…
- Problem: Find the length of the longest common subsequence of two version strings. python def lcs(a, b): dp = [[0] (len(b) + 1) for in…