Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count subarrays whose maximum lies in [L, R] in one pass.

Problem: Count subarrays whose maximum lies in [L, R] in one pass.
def count(a, L, R):
    last_bad = last_ok = -1; res = 0
    for i, x in enumerate(a):
        if x > R: last_bad = i
        if x >= L: last_ok = i
        res += max(0, last_ok - last_bad)
    return res
print(count([3, 1, 6, 2, 9, 4, 5], 3, 6))
What is printed?
  1. A. 10
  2. B. 28
  3. C. 11
  4. D. 13

Correct answer: C. 11

For each right end i, valid left ends lie after the last element > R and at or before the last element ≥ L, giving last_ok − last_bad choices. The 9 resets everything; the total 11 matches checking all 28 subarrays.

More Coding Interview Problems questions

Exams that ask this topic