ans
to 0
to store the count of valid subarrays.st
to store indices of elements.nums
using index i
.
a. While the stack is not empty and nums[i]
is less than nums[st.top()]
, pop elements from the stack.
b. For each popped element, add i - st.top()
to ans
.
c. Push the current index i
into the stack.nums.size() - st.top()
to ans
.ans
.