Data Structures & AlgorithmsModerateTCS CodeVita · Microsoft SDE OA
Houses have values e = [2, 7, 9, 3, 1, 8, 4, 6] and a robber cannot take two adjacent houses. Find the maximum sum that can be taken, using the DP that keeps the best value with and without the last house.
Houses have values e = [2, 7, 9, 3, 1, 8, 4, 6] and a robber cannot take two adjacent houses. Find the maximum sum that can be taken, using the DP that keeps the best value with and without the last house.
e=[2,7,9,3,1,8,4,6]
take=skip=0
for x in e:
take,skip=skip+x,max(take,skip)
print(max(take,skip))What is printed?- A. 16
- B. 40
- C. 30
- D. 25
Correct answer: D. 25
The DP keeps two states per house: best sum when the house is taken (then the previous is skipped) and best when it is not. Taking every house ignores adjacency, summing the largest four values ignores positions, and alternating houses gives a fixed pattern that is not optimal.
More Coding Interview Problems questions
- Count the subarrays of v = [4, 6, 2, 1, 7, 3, 5, 1] whose XOR equals 0, considering only subarrays of length at least 3. Brute-force all…
- Histogram bars have heights h = [2, 1, 5, 6, 2, 3]. What is the area of the largest rectangle that fits entirely inside the histogram…
- What is the maximum sum of a non-empty subarray in the circular array [8, -8, 9, -9, 10, -11, 12], where the subarray may wrap from the…
- What is the maximum product of a non-empty contiguous subarray of [2, -5, -2, -4, 3]?
- What is the minimum number of coins needed to make an amount of 18 using unlimited coins of denominations {1, 6, 10}?
- The array is [3, 3, 4, 4, 5, 1, 2, 2, 6, 3, 7]. What is the length of its longest non-decreasing (not strictly increasing) subsequence?