Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: A thief robs houses in a row but cannot rob two adjacent houses. Find the maximum loot.
Problem: A thief robs houses in a row but cannot rob two adjacent houses. Find the maximum loot.
def rob(a):
take = skip = 0
for x in a:
take, skip = skip + x, max(take, skip)
return max(take, skip)
print(rob([2, 7, 9, 3, 1]), rob([2, 1, 1, 2]))What is printed?- A. 12 4
- B. 11 4
- C. 12 3
- D. 10 4
Correct answer: A. 12 4
take = best ending by robbing this house, skip = best without it. [2, 7, 9, 3, 1] → 2 + 9 + 1 = 12. [2, 1, 1, 2] → rob both ends = 4; taking every other house from index 0 gives only 3. O(n), O(1).
More Coding Interview Problems questions
- Problem: Same robbery, but the houses form a circle (first and last are adjacent). python def line(a): take = skip = 0 for x in a: take…
- 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)…