Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Children stand in a line with ratings; each gets ≥ 1 candy and a child with a higher rating than a NEIGHBOUR must get more than that neighbour. Find the minimum total.
Problem: Children stand in a line with ratings; each gets ≥ 1 candy and a child with a higher rating than a NEIGHBOUR must get more than that neighbour. Find the minimum total.
def candy(r):
n = len(r); c = [1] * n
for i in range(1, n):
if r[i] > r[i-1]: c[i] = c[i-1] + 1
for i in range(n - 2, -1, -1):
if r[i] > r[i+1]: c[i] = max(c[i], c[i+1] + 1)
return sum(c)
print(candy([4, 6, 4, 5, 6, 2]))What is printed?- A. 9
- B. 10
- C. 8
- D. 16
Correct answer: B. 10
Left pass gives [1, 2, 1, 2, 3, 1]; the right pass changes nothing because each peak already exceeds its right neighbour, so the total is 10. Running only the right-to-left pass gives 8, overwriting with c[i+1] + 1 instead of taking the max gives 9, and handing out candies by global rating rank gives 16.
More Coding Interview Problems questions
- Problem: Count the ways to make amount 5 from coins [1, 2, 5]. A developer wrote the loops in this order. python def ways(coins, amt): dp…
- Problem: Find the length of the longest palindromic subsequence of s and the minimum number of insertions that make s a palindrome. python…
- Problem: Matrices A1..A6 have dimensions given by d (Ai is d[i−1] × d[i]). Find the minimum number of scalar multiplications to compute…
- Problem: With e identical eggs, find the minimum number of drops that always identifies the critical floor of an f-floor building. The…
- Problem: Count the ways to place n non-attacking queens on an n × n board. python def queens(n): cols, d1, d2 = set(), set(), set() def…
- Problem: Count the DISTINCT subsets (as multisets) of a list that contains duplicates, using backtracking that skips equal siblings…