Data Structures & AlgorithmsVery hardProduct Company SDE · greedy OA
Problem: What is the maximum number of pairwise non-overlapping non-empty subarrays of [1, -1, 2, -2, 3, -3] each having sum zero? Run the greedy code.
Problem: What is the maximum number of pairwise non-overlapping non-empty subarrays of [1, -1, 2, -2, 3, -3] each having sum zero? Run the greedy code.
a = [1, -1, 2, -2, 3, -3]
seen = {0}
s = 0
cnt = 0
for x in a:
s += x
if s in seen:
cnt += 1
seen = {0}
s = 0
else:
seen.add(s)
print(cnt)What is printed?- A. 2
- B. 4
- C. 3
- D. 6
Correct answer: C. 3
Greedily closing a zero-sum block as soon as one is seen gives [1,-1], [2,-2] and [3,-3], which is optimal because the earliest finishing block leaves the most room.
More Coding Interview Problems questions
- Problem: How many 3-element subsets of {1, 2, 3, 4, 5, 6} have a sum divisible by 3? Run the code. python from itertools import…
- Problem: Minimum number of deletions so that no two adjacent characters of 'aaabbb' are equal. Run the code. python s = 'aaabbb' kept = []…
- Problem: What is the maximum product of positive integer parts when 10 is split into at least two parts? Run the DP. python n = 10 dp =…
- Problem: How many integer partitions does 6 have (unordered sums of positive integers equal to 6)? Run the DP. python n = 6 p = [1] + [0]…
- Problem: How many ordered pairs (x, y) with 1 <= x, y <= 10 have x y <= 10? Run the code. python print(sum(1 for x in range(1, 11) for y…
- Problem: How many integers in [1, 1000] contain the digit 0? Run the code. python print(sum(1 for x in range(1, 1001) if '0' in str(x)))…