ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def sum_min(a):
    MOD = 10**9 + 7
    st = []
    total = 0
    cur = 0
    for x in a:
        cnt = 1
        while st and st[-1][0] >= x:
            v, c = st.pop()
            cnt += c
            cur -= v * c
        st.append((x, cnt))
        cur += x * cnt
        total += cur
    return total % MOD
print(sum_min([3, 1, 2, 4]), sum_min([11, 81, 94, 43, 3]))
  1. A. 17 443
  2. B. 17 444
  3. C. 16 444
  4. D. 18 444

Correct answer: B. 17 444

A monotonic stack tracks, for each new element, the running total of minima over all subarrays that end there. [3, 1, 2, 4] gives 17, and the second array gives 444.

More Python Programming questions

Exams that ask this topic