ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def at_most(a, k):
    l = s = c = 0
    for r, x in enumerate(a):
        s += x
        while s > k:
            s -= a[l]
            l += 1
        c += r - l + 1
    return c
def exact(a, k):
    return at_most(a, k) - at_most(a, k - 1)
print(exact([1, 2, 1, 2, 1], 3), exact([1, 1, 1], 2))
  1. A. 3 2
  2. B. 4 3
  3. C. 4 2
  4. D. 5 2

Correct answer: C. 4 2

With non-negative values, subarrays with sum at most k can be counted by a sliding window. Exact count equals at_most(k) minus at_most(k-1), giving 4 for the first array and 2 for the second.

More Python Programming questions

Exams that ask this topic