Data Structures & AlgorithmsHardProduct Company SDE · greedy round
Problem: Children stand in a line with ratings [1, 0, 2]. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more candies. What is the minimum total number of candies? Run the two-pass code.
Problem: Children stand in a line with ratings [1, 0, 2]. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more candies. What is the minimum total number of candies? Run the two-pass code.
r = [1, 0, 2]
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)
print(sum(c))What is printed?- A. 5
- B. 4
- C. 6
- D. 3
Correct answer: A. 5
The left-to-right pass gives [1, 1, 2] and the right-to-left pass fixes the first child to 2, giving [2, 1, 2] with total 5. Using only one pass gives 4 and violates the rule for the first child.
More Coding Interview Problems questions
- Problem: Water is poured into a container of heights [1, 8, 6, 2, 5, 4, 8, 3, 7]. Choose two lines to maximise the area of water they…
- Problem: Trucks carry boxes: each truck type is (count, units per box), and at most 10 boxes fit on the truck. Maximise units per truck…
- Problem: How many contiguous subarrays of [1, 2, 3, 4, 5] have sum exactly 5? Run the code. python a = [1, 2, 3, 4, 5] print(sum(1 for i…
- Problem: What is the length of the longest zigzag subsequence (values alternate strictly up and down) of [1, 7, 4, 9, 2, 5]? Run the DP…
- Problem: Two piles of stones (values [1, 6, 11, 5]) are to be divided into two groups whose sums differ as little as possible. What is the…
- Problem: You have 2 eggs and a building with 10 floors. What is the minimum number of drops needed in the worst case to find the highest…